Rewriting same code in different methods - return-type

I have written the following code however trying to figure out how rewrite it by including parameters and boolean values if possible where main method requests user input and then calls upon the methods in order to produce the output:
import java.util.*;
class Congress
{
public static void main (String [] args)
{
int age, citizen, i, r;
citizen = 0;
i = 0;
r = 0;
age = -1;
Scanner keyboard = new Scanner(System.in);
System.out.println ("CONGRESS ELIGIBILITY");
for (age = -1; age < 0; r++)
{
System.out.println();
System.out.print ("Enter age of candidate: ");
age = keyboard.nextInt();
System.out.print ("Enter years of US citizenship: ");
citizen = keyboard.nextInt();
if (age <= 0)
{
System.out.print ("Please enter a proper age. ");
}
}
if (age >= 25 && citizen >= 7) {
i++;
}
if (age >= 30 && citizen >= 9) {
i++;
}
if (i == 0) {
System.out.println ("The candidate is not eligible for election to either the House of Representatives or the Senate.");
}
if (i == 1) {
System.out.println ("The candidate is eligible for election to the House of Representatives but is not eligible for election to the Senate.");
}
if (i == 2) {
System.out.println ("The candidate is eligible for election to both the House of Representatives and the Senate.");
}
}
}

/*
* graphs - Congress.java, Nov 18, 2013 5:38:15 PM
*
/
import java.util.;
/**
* The Class Congress.
*
* #author Rajakrishna V. Reddy
* #version 1.0
*
*/
class Congress
{
/**
* Eligible for senate.
*
* #param age
* the age
* #param lengthOfCitizenship
* the length of citizenship
* #return true, if successful
*/
public static boolean eligibleForSenate(int age, int lengthOfCitizenship)
{
return age >= 30 && lengthOfCitizenship >= 9;
}
/**
* Eligible for house.
*
* #param age
* the age
* #param lengthOfCitizenship
* the length of citizenship
* #return true, if successful
*/
public static boolean eligibleForHouse(int age, int lengthOfCitizenship)
{
return age >= 25 && lengthOfCitizenship >= 7;
}
/**
* The main method.
*
* #param args
* the arguments
*/
public static void main(String[] args)
{
int age, citizen, i, r;
citizen = 0;
i = 0;
r = 0;
age = -1;
final Scanner keyboard = new Scanner(System.in);
System.out.println("CONGRESS ELIGIBILITY");
for (age = -1; age < 0; r++)
{
System.out.println();
System.out.print("Enter age of candidate: ");
age = keyboard.nextInt();
System.out.print("Enter years of US citizenship: ");
citizen = keyboard.nextInt();
if (age <= 0)
{
System.out.print("Please enter a proper age. ");
}
}
try
{
keyboard.close();
}
finally
{
}
final boolean eligibleForHouse = eligibleForHouse(age, citizen);
final boolean eligibleForSenate = eligibleForSenate(age, citizen);
if (eligibleForHouse && !eligibleForSenate)
{
System.out.println("The candidate is eligible for election to the House of Representatives but is not eligible for election to the Senate.");
}
if (!eligibleForHouse && !eligibleForSenate)
{
System.out.println("The candidate is not eligible for election to either the House of Representatives or the Senate.");
}
if (eligibleForHouse && eligibleForSenate)
{
System.out.println("The candidate is eligible for election to both the House of Representatives and the Senate.");
}
}
}

Related

Linked list by reference or by value?

Here is the question. Say a linked list is implemented as follows (Java):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
Consider the linked list:
1 -> 2 -> 3 -> 4
I do something like:
ListNode newHead = head;
newHead = head.next.next;
//Now newHead is pointing to (3) in the linked list.
Now I perform the magic:
newHead.val = 87
The linked list becomes:
1 -> 2 -> 87 -> 4
If I printed head and NOT newHead.
Why is this? I didn't modify anything with head but it still changed?
So you can use this:
Node Class:
public class IntNode {
int value;
IntNode next;
public IntNode(int value) {
this.value = value;
}
}
Singly Linked List Class:
/**
* A singly-linked list of integer values with fast addFirst and addLast methods
*/
public class LinkedIntList {
IntNode first;
IntNode last;
int size;
/**
* Return the integer value at position 'index'
*/
int get(int index) {
return getNode(index).value;
}
/**
* Set the integer value at position 'index' to 'value'
*/
void set(int index, int value) {
getNode(index).value = value;
}
/**
* Returns whether the list is empty (has no values)
*/
boolean isEmpty() {
return size == 0;
}
/**
* Inserts 'value' at position 0 in the list.
*/
void addFirst(int value) {
IntNode newNode = new IntNode(value);
newNode.next = first;
first = newNode;
if(last == null)
last = newNode;
size++;
}
/**
* Appends 'value' at the end of the list.
*/
void addLast(int value) {
IntNode newNode = new IntNode(value);
if(isEmpty())
first = newNode;
else
last.next = newNode;
last = newNode;
size++;
}
/**
* Removes and returns the first value of the list.
*/
int removeFirst() {
if(isEmpty()) {
System.out.println("RemoveFirst() on empty list!");
System.exit(-1);
}
int value = first.value;
if(first == last) {
// List has only one element, so just clear it
clear();
}
else {
first = first.next;
size--;
}
return value;
}
/**
* Removes and returns the last value of the list.
*/
int removeLast() {
if(isEmpty()) {
System.out.println("RemoveLast() on empty list!");
System.exit(-1);
}
int value = last.value;
if(first == last) {
// List has only one element, so just clear it
clear();
}
else {
// List has more than one element
IntNode currentNode = first;
while(currentNode.next != last)
currentNode = currentNode.next;
currentNode.next = null;
last = currentNode;
size--;
}
return value;
}
/**
* Removes all values from the list, making the list empty.
*/
void clear() {
first = last = null;
size = 0;
}
/**
* Returns a new int-array with the same contents as the list.
*/
int[] toArray() {
int[] array = new int[size];
int i = 0;
for(IntNode n = first; n != null; n = n.next, i++)
array[i] = n.value;
return array;
}
/**
* For internal use only.
*/
IntNode getNode(int index) {
if(index < 0 || index >= size) {
System.out.println("GetNode() with invalid index: " + index);
System.exit(-1);
}
IntNode current = first;
for(int i = 0; i < index; i++)
current = current.next;
return current;
}
}
See the comments in the code for description.

Can someone with GA experience examine my fitness function?

Here is my problem, I'm modifying code I found for Genetic Algorithms to do numerical optimization of a function. Essentially, given a function F and our Desired Value, the program uses GA to searches for values of x and y which provide the appropriate Desired Value.
I keep tinkering with my fitness function, which I feel is the root of the issue.
The basic code break down is:
Generate a random chromosome population
Use a bubble sort based on each chromosomes fitness
Check if any of them happen to solve the function
If one solves it, then stop and print it
Else,
Generate children based on the parents
Sort, check the best answer, loop
I hope someone can point me in the right direction I'm going to dissect it again some more tonight but I seem to have hit a snag on this. For more complex functions than that I have hard coded, it seems to converge around a random percentage (usually less than 20)... but it should be much closer to 0. The simple coded function keeps returning around 99% difference... so I'm not 100% on whats up.
import java.util.*;
import java.util.Comparator;
import java.util.TreeMap;
/**
* Modified from a file created Jul 9, 2003
* Original #author Fabian Jones
* Modified #author Cutright
* #version 2
*/
public class ScratchGA
{
private static int NUM_CHROMOSOMES = 100; //num of chromosomes in population
private static double MUTATE = .01; //chance of a mutation i.e. 88.8%
private static int desiredValue = 60466176; //desired value of function
private static int cutoff = 1000; // number of iterations before cut off
private static int longPrint = 0; //1 means print out each iteration of the population
private boolean done = false;
private Chromosome[] population;
int iteration = 0;
/**
* Constructor for objects of class ScratchGA
*/
public ScratchGA()
{
generateRandomPopulation(NUM_CHROMOSOMES);
printPopulation();
}
/**
* Generate a random population of chromosomes - WORKS
*
*/
private void generateRandomPopulation(int pop)
{
System.out.println("Generating random population of " + pop + ", now." +"\n");
population = new Chromosome[pop];
for(int i=0; i<pop; i++)
{
int rand = (int)(Math.random()*4095); // Range 0 to 4095
population[i] = (new Chromosome(rand, 12));
}
}
/**
* Codesaver for generating a new line in the output
*/
private void newLine()
{
System.out.println("\n");
}
/**
* Prints the population (the chromosomes)
*/
private void printPopulation()
{
int x=1; // variable to print 10 chromosomes on a line
if (iteration==0)
{
System.out.println("Initial population: " + "\n" );
}
else
{
if (longPrint ==1)
{
System.out.println("Population " + iteration + " :" + "\n");
for(int i=0; i<=(NUM_CHROMOSOMES-1); i++)
{
System.out.print(population[i] + " ");
if(x == 10)
{
newLine();
x=1;
}
else
{
x++;
}
}
newLine();
}
else
{
System.out.println("Best answer for iteration " + iteration + " is: " + population[0] + " with a % difference of " +population[0].getFitness());
newLine();
}
}
}
/**
* Start
* Bubblesort initial population by their fitness, see if the first chromosome
* in the sorted array satisfies our constraint.
* IF done ==true or max num of iterations
* Print best solution and its fitness
* ELSE
* generate new population based on old one, and continue on
*/
public void start()
{
// System.out.println("Starting bubblesort... Please Wait.");
bubbleSort();
//System.out.println("After Bubblesort: " );
//printPopulation();
topFitness();
if(done || iteration==cutoff){
System.out.println("DONE!!");
System.out.println("Best solution: " + population[0] + " % Difference: " + population[0].getFitness());
}
else{
iteration++;
generateNewPopulation();
printPopulation();
start();
}
}
/**
* If the top chromosomes fitness (after being sorted by bubblesort) is 100%
* done == true
*/
private void topFitness()
{
if (population[0].getFitness() == 0)
{
done = true;
}
}
/**
* Called from chromosome,
* Tests the x and y values in the function and returns their output
*/
public static double functionTest(int x, int y)
{
return (3*x)^(2*y); // From our desired value we're looking for x=2, y=5
}
/**
* Returns the desired outcome of the function, with ideal x and y
* Stored above in a private static
*/
public static int getDesired()
{
return desiredValue;
}
/**
* Sort Chromosome array, based on fitness
* utilizes a bubblesort
*/
private void bubbleSort()
{
Chromosome temp;
for(int i=0; i<NUM_CHROMOSOMES; i++){
for(int j=1; j<(NUM_CHROMOSOMES-i); j++){
if(population[j-1].getFitness() > population[j].getFitness())
{
//swap elements
temp = population[j-1];
population[j-1] = population[j];
population[j] = temp;
}
}
}
}
/**
* Top 30: Elitism
* Next 60: Offspring of Elitists
* Next 10: Random
*/
private void generateNewPopulation(){
System.out.println("***Generating New Population");
Chromosome[] temp = new Chromosome[100];
for (int i = 0; i < 30; i++)
{
Chromosome x = population[i];
if (shouldMutate())
mutate(x);
temp[i]=x;
}
for (int i = 0; i < 30; i++)
{
temp[i+30] =cross1(population[i], population[i+1]);
temp[i+60] = cross2(population[i], population[i+1]);
}
for (int i = 90; i<100; i++)
{
int rand = (int)(Math.random()*4095); // Range 0 to 4095
Chromosome x = new Chromosome(rand, 12);
temp[i] = x;
}
population = temp;
}
/**
* First cross type, with two parents
*/
private Chromosome cross1(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
int num = (int)(Math.random()*length); // number from 0 to length-1
String newBitString = bitS2.substring(0, num) + bitS1.substring(num, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
/**
* Second cross type, parents given in same order as first, but reverses internal workings
*/
private Chromosome cross2(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
int num = (int)(Math.random()*length); // number from 0 to length-1
String newBitString = bitS2.substring(0, num) + bitS1.substring(num, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
/**
* Returns a boolean of whether a character should mutate based on the mutation value at top
*/
private boolean shouldMutate(){
double num = Math.random()*100;
return (num <= MUTATE);
}
/**
* Returns a boolean of whether a character should mutate based on the mutation value at top
*/
private void mutate(Chromosome offspring){
String s = offspring.getBitString();
int num = s.length();
int index = (int) (Math.random()*num);
String newBit = flip(s.substring(index, index+1));
String newBitString = s.substring(0, index) + newBit + s.substring(index+1, s.length());
offspring.setBitString(newBitString);
}
/**
* Flips bits in a string 1 to 0, 0 to 1
*/
private String flip(String s){
return s.equals("0")? "1":"0";
}
}
import java.lang.Comparable;
import java.math.*;
/**
* Modified from a file created on Jul 9, 2003
* Unsure of original author
*
*/
public class Chromosome implements Comparable
{
protected String bitString;
/**
* Constructor for objects of class Chromosome
*/
public Chromosome()
{
}
public Chromosome(int value, int length)
{
bitString = convertIntToBitString(value, length);
}
public void setBitString(String s)
{
bitString = s;
}
public String getBitString()
{
return bitString;
}
public int compareTo(Object o)
{
Chromosome c = (Chromosome) o;
int num = countOnes(this.bitString) - countOnes(c.getBitString());
return num;
}
public double getFitness()
{
String working = bitString;
int x1 = Integer.parseInt(working.substring(0,6),2);
int x2 = Integer.parseInt(working.substring(6),2);
double result = ScratchGA.functionTest(x1,x2);
double percentDiff = ((ScratchGA.getDesired() - result)/ScratchGA.getDesired())*100;
if (percentDiff >= 0)
{
return percentDiff;
}
else
{
return -percentDiff;
}
}
public boolean equals(Object o)
{
if(o instanceof Chromosome)
{
Chromosome c = (Chromosome) o;
return c.getBitString().equals(bitString);
}
return false;
}
public int hashCode()
{
return bitString.hashCode();
}
public String toString()
{
return bitString;
}
public static int countOnes(String bits)
{
int sum = 0;
for(int i = 0; i < bits.length(); ++ i){
String test = bits.substring(i, i+1);
if(test.equals("1")){
sum = sum + 1;
}
}
return sum;
}
public static String convertIntToBitString(int val, int length)
{
int reval = val;
StringBuffer bitString = new StringBuffer(length);
for(int i = length-1; i >=0; --i ){
if( reval - (Math.pow(2, i)) >= 0 ){
bitString.append("1");
reval = (int) (reval - Math.pow(2, i));
}
else{
bitString.append("0");
}
}
return bitString.toString();
}
public static void main(String[] args
){
//System.out.println(convertIntToBitString(2046, 10));
Chromosome c = new Chromosome(1234, 10);
//System.out.println(c.fitness());
}
}
Actually, it was a simple error that eluded me, that I should have caught. The major issue was in using return (3*x)^(2*y); ^ is a bitwise XOR in java, but an exponent. (Whoops) The problem was rectified using Math.pow(3*x,2*y); ...and a little double check of the fitness function had it up and running with some other minor changes :)

Finding the longest repeated substring

What would be the best approach (performance-wise) in solving this problem?
I was recommended to use suffix trees. Is this the best approach?
Check out this link: http://introcs.cs.princeton.edu/java/42sort/LRS.java.html
/*************************************************************************
* Compilation: javac LRS.java
* Execution: java LRS < file.txt
* Dependencies: StdIn.java
*
* Reads a text corpus from stdin, replaces all consecutive blocks of
* whitespace with a single space, and then computes the longest
* repeated substring in that corpus. Suffix sorts the corpus using
* the system sort, then finds the longest repeated substring among
* consecutive suffixes in the sorted order.
*
* % java LRS < mobydick.txt
* ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th'
*
* % java LRS
* aaaaaaaaa
* 'aaaaaaaa'
*
* % java LRS
* abcdefg
* ''
*
*************************************************************************/
import java.util.Arrays;
public class LRS {
// return the longest common prefix of s and t
public static String lcp(String s, String t) {
int n = Math.min(s.length(), t.length());
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i))
return s.substring(0, i);
}
return s.substring(0, n);
}
// return the longest repeated string in s
public static String lrs(String s) {
// form the N suffixes
int N = s.length();
String[] suffixes = new String[N];
for (int i = 0; i < N; i++) {
suffixes[i] = s.substring(i, N);
}
// sort them
Arrays.sort(suffixes);
// find longest repeated substring by comparing adjacent sorted suffixes
String lrs = "";
for (int i = 0; i < N - 1; i++) {
String x = lcp(suffixes[i], suffixes[i+1]);
if (x.length() > lrs.length())
lrs = x;
}
return lrs;
}
// read in text, replacing all consecutive whitespace with a single space
// then compute longest repeated substring
public static void main(String[] args) {
String s = StdIn.readAll();
s = s.replaceAll("\\s+", " ");
StdOut.println("'" + lrs(s) + "'");
}
}
Have a look at http://en.wikipedia.org/wiki/Suffix_array as well - they are quite space-efficient and have some reasonably programmable algorithms to produce them, such as "Simple Linear Work Suffix Array Construction" by Karkkainen and Sanders
Here is a simple implementation of longest repeated substring using simplest suffix tree. Suffix tree is very easy to implement in this way.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
class Node
{
public:
char ch;
unordered_map<char, Node*> children;
vector<int> indexes; //store the indexes of the substring from where it starts
Node(char c):ch(c){}
};
int maxLen = 0;
string maxStr = "";
void insertInSuffixTree(Node* root, string str, int index, string originalSuffix, int level=0)
{
root->indexes.push_back(index);
// it is repeated and length is greater than maxLen
// then store the substring
if(root->indexes.size() > 1 && maxLen < level)
{
maxLen = level;
maxStr = originalSuffix.substr(0, level);
}
if(str.empty()) return;
Node* child;
if(root->children.count(str[0]) == 0) {
child = new Node(str[0]);
root->children[str[0]] = child;
} else {
child = root->children[str[0]];
}
insertInSuffixTree(child, str.substr(1), index, originalSuffix, level+1);
}
int main()
{
string str = "banana"; //"abcabcaacb"; //"banana"; //"mississippi";
Node* root = new Node('#');
//insert all substring in suffix tree
for(int i=0; i<str.size(); i++){
string s = str.substr(i);
insertInSuffixTree(root, s, i, s);
}
cout << maxLen << "->" << maxStr << endl;
return 1;
}
/*
s = "mississippi", return "issi"
s = "banana", return "ana"
s = "abcabcaacb", return "abca"
s = "aababa", return "aba"
*/
the LRS problem is one that is best solved using either a suffix tree or a suffix array. Both approaches have a best time complexity of O(n).
Here is an O(nlog(n)) solution to the LRS problem using a suffix array. My solution can be improved to O(n) if you have a linear construction time algorithm for the suffix array (which is quite hard to implement). The code was taken from my library. If you want more information on how suffix arrays work make sure to check out my tutorials
/**
* Finds the longest repeated substring(s) of a string.
*
* Time complexity: O(nlogn), bounded by suffix array construction
*
* #author William Fiset, william.alexandre.fiset#gmail.com
**/
import java.util.*;
public class LongestRepeatedSubstring {
// Example usage
public static void main(String[] args) {
String str = "ABC$BCA$CAB";
SuffixArray sa = new SuffixArray(str);
System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());
str = "aaaaa";
sa = new SuffixArray(str);
System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());
str = "abcde";
sa = new SuffixArray(str);
System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());
}
}
class SuffixArray {
// ALPHABET_SZ is the default alphabet size, this may need to be much larger
int ALPHABET_SZ = 256, N;
int[] T, lcp, sa, sa2, rank, tmp, c;
public SuffixArray(String str) {
this(toIntArray(str));
}
private static int[] toIntArray(String s) {
int[] text = new int[s.length()];
for(int i=0;i<s.length();i++)text[i] = s.charAt(i);
return text;
}
// Designated constructor
public SuffixArray(int[] text) {
T = text;
N = text.length;
sa = new int[N];
sa2 = new int[N];
rank = new int[N];
c = new int[Math.max(ALPHABET_SZ, N)];
construct();
kasai();
}
private void construct() {
int i, p, r;
for (i=0; i<N; ++i) c[rank[i] = T[i]]++;
for (i=1; i<ALPHABET_SZ; ++i) c[i] += c[i-1];
for (i=N-1; i>=0; --i) sa[--c[T[i]]] = i;
for (p=1; p<N; p <<= 1) {
for (r=0, i=N-p; i<N; ++i) sa2[r++] = i;
for (i=0; i<N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
Arrays.fill(c, 0, ALPHABET_SZ, 0);
for (i=0; i<N; ++i) c[rank[i]]++;
for (i=1; i<ALPHABET_SZ; ++i) c[i] += c[i-1];
for (i=N-1; i>=0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
for (sa2[sa[0]] = r = 0, i=1; i<N; ++i) {
if (!(rank[sa[i-1]] == rank[sa[i]] &&
sa[i-1]+p < N && sa[i]+p < N &&
rank[sa[i-1]+p] == rank[sa[i]+p])) r++;
sa2[sa[i]] = r;
} tmp = rank; rank = sa2; sa2 = tmp;
if (r == N-1) break; ALPHABET_SZ = r + 1;
}
}
// Use Kasai algorithm to build LCP array
private void kasai() {
lcp = new int[N];
int [] inv = new int[N];
for (int i = 0; i < N; i++) inv[sa[i]] = i;
for (int i = 0, len = 0; i < N; i++) {
if (inv[i] > 0) {
int k = sa[inv[i]-1];
while( (i + len < N) && (k + len < N) && T[i+len] == T[k+len] ) len++;
lcp[inv[i]-1] = len;
if (len > 0) len--;
}
}
}
// Finds the LRS(s) (Longest Repeated Substring) that occurs in a string.
// Traditionally we are only interested in substrings that appear at
// least twice, so this method returns an empty set if this is not the case.
// #return an ordered set of longest repeated substrings
public TreeSet <String> lrs() {
int max_len = 0;
TreeSet <String> lrss = new TreeSet<>();
for (int i = 0; i < N; i++) {
if (lcp[i] > 0 && lcp[i] >= max_len) {
// We found a longer LRS
if ( lcp[i] > max_len )
lrss.clear();
// Append substring to the list and update max
max_len = lcp[i];
lrss.add( new String(T, sa[i], max_len) );
}
}
return lrss;
}
public void display() {
System.out.printf("-----i-----SA-----LCP---Suffix\n");
for(int i = 0; i < N; i++) {
int suffixLen = N - sa[i];
String suffix = new String(T, sa[i], suffixLen);
System.out.printf("% 7d % 7d % 7d %s\n", i, sa[i],lcp[i], suffix );
}
}
}
public class LongestSubString {
public static void main(String[] args) {
String s = findMaxRepeatedString("ssssssssssss this is a ddddddd word with iiiiiiiiiis and loads of these are ppppppppppppps");
System.out.println(s);
}
private static String findMaxRepeatedString(String s) {
Processor p = new Processor();
char[] c = s.toCharArray();
for (char ch : c) {
p.process(ch);
}
System.out.println(p.bigger());
return new String(new char[p.bigger().count]).replace('\0', p.bigger().letter);
}
static class CharSet {
int count;
Character letter;
boolean isLastPush;
boolean assign(char c) {
if (letter == null) {
count++;
letter = c;
isLastPush = true;
return true;
}
return false;
}
void reassign(char c) {
count = 1;
letter = c;
isLastPush = true;
}
boolean push(char c) {
if (isLastPush && letter == c) {
count++;
return true;
}
return false;
}
#Override
public String toString() {
return "CharSet [count=" + count + ", letter=" + letter + "]";
}
}
static class Processor {
Character previousLetter = null;
CharSet set1 = new CharSet();
CharSet set2 = new CharSet();
void process(char c) {
if ((set1.assign(c)) || set1.push(c)) {
set2.isLastPush = false;
} else if ((set2.assign(c)) || set2.push(c)) {
set1.isLastPush = false;
} else {
set1.isLastPush = set2.isLastPush = false;
smaller().reassign(c);
}
}
CharSet smaller() {
return set1.count < set2.count ? set1 : set2;
}
CharSet bigger() {
return set1.count < set2.count ? set2 : set1;
}
}
}
I had an interview and I needed to solve this problem. This is my solution:
public class FindLargestSubstring {
public static void main(String[] args) {
String test = "ATCGATCGA";
System.out.println(hasRepeatedSubString(test));
}
private static String hasRepeatedSubString(String string) {
Hashtable<String, Integer> hashtable = new Hashtable<>();
int length = string.length();
for (int subLength = length - 1; subLength > 1; subLength--) {
for (int i = 0; i <= length - subLength; i++) {
String sub = string.substring(i, subLength + i);
if (hashtable.containsKey(sub)) {
return sub;
} else {
hashtable.put(sub, subLength);
}
}
}
return "No repeated substring!";
}}
There are way too many things that affect performance for us to answer this question with only what you've given us. (Operating System, language, memory issues, the code itself)
If you're just looking for a mathematical analysis of the algorithm's efficiency, you probably want to change the question.
EDIT
When I mentioned "memory issues" and "the code" I didn't provide all the details. The length of the strings you will be analyzing are a BIG factor. Also, the code doesn't operate alone - it must sit inside a program to be useful. What are the characteristics of that program which impact this algorithm's use and performance?
Basically, you can't performance tune until you have a real situation to test. You can make very educated guesses about what is likely to perform best, but until you have real data and real code, you'll never be certain.

0 1 matrix balancing

On wikipedia http://en.wikipedia.org/wiki/Dynamic_programming#A_type_of_balanced_0.E2.80.931_matrix, counting the number of 0 1 balanced matrices is given as an example of dynamic programming. But I found it really hard to implement the algorithm given there. Is there a better algorithm?
If not, then can anyone kindly explain the algorithm presented there in a way that makes it easier to implement. Like what would be the recurrence relation in this algorithm? Because once I have found it, it would be easy to do memoization.
Also can any one tell that why this particular problem seems so much harder than all the other problems given on that page.
Dynamic programming would be faster, but here is a simple way for enumeration.
Balanced matrix: bicolorable 0-1 matrix. Here s is the dimension of the 0-1 balanced square matrix, L[p][q] is an entry of the matrix. Initially call enumerate(s,1,1).
int enumerate(int s, int p,int q){
if(p>s) {
printmatrix(L);
return 0;
}
if(p>=3 && q>=3){
int min = p;if(p>q){min=q;}
if L[1...min][1...min] is not a balanced matrix, then return 0;
}
if(q<=s) {
L[p][q] = 1;
enumerate(s,p,q+1);
if(p!=q){
L[p][q] = 0;
enumerate(s,p,q+1);
}
}
if(q>s) {
enumerate(s,p+1,1);
}
return 0;
}
Dynamic programming solution
import java.util.HashMap;
import java.util.Map;
public class Balanced01Matrix {
//Variable to hold all possible row permutation
private int[][] rowPerms;
//Mapping function f((n/2,n/2),(n/2,n/2)......(n/2,n/2))
Map<String, Integer> arrangeFunction;
int rowCounter = 0;
/**
* #param args
*/
public static void main(String[] args) {
Balanced01Matrix bm = new Balanced01Matrix();
int n = 4;
int rows = bm.combination(n, n/2);
bm.rowPerms = new int[rows][n];
//Getting all the row permuation with n/2 '0' and n/2 '1'
bm.getAllCombination(n/2, n/2, n, new int[n]);
//bm.printAllCombination();
bm.arrangeFunction = new HashMap<String, Integer>();
//Variable to hold vector ((n/2,n/2),(n/2,n/2),......(n/2,n/2))
int[][] digitsRemaining = new int[n][2];
for(int i=0;i<n;i++){
digitsRemaining[i][0]=n/2;
digitsRemaining[i][1]=n/2;
}
//Printing total number of combination possible for nxn balanced matrix
System.out.println(bm.possibleCombinations(digitsRemaining, n));
}
/**
* Method to get all permutation of a row with n/2 zero and n/2 one
* #param oneCount
* #param zeroCount
* #param totalCount
* #param tmpArr
*/
private void getAllCombination(int oneCount, int zeroCount, int totalCount, int[] tmpArr){
if(totalCount>0){
if(oneCount > 0){
tmpArr[totalCount-1] = 1;
getAllCombination(oneCount-1, zeroCount, totalCount-1, tmpArr);
}
if(zeroCount > 0){
tmpArr[totalCount-1] = 0;
getAllCombination(oneCount, zeroCount-1, totalCount-1, tmpArr);
}
}else{
rowPerms[rowCounter++] = tmpArr.clone();
}
}
/**
* Recursive function to calculate all combination possible for a given vector and level
* #param digitsRemaining
* #param level
* #return
*/
private int possibleCombinations(int[][] digitsRemaining, int level){
//Using memoization
if(arrangeFunction.containsKey(getStringForDigitsRemaining(digitsRemaining))){
return arrangeFunction.get(getStringForDigitsRemaining(digitsRemaining));
}
int totalCombination = 0;
for(int[] row: rowPerms){
int i=0;
int[][] tmpArr = createCopy(digitsRemaining);
for(;i<row.length;i++){
if(row[i]==0){
if(tmpArr[i][0] - 1 >= 0){
tmpArr[i][0] -= 1;
}else
break;
}else{
if(tmpArr[i][1] - 1 >= 0){
tmpArr[i][1] -= 1;
}else
break;
}
}
//If row permutation is successfully used for this level
//else try next permuation
if(i==row.length){
//If last row of matrix return 1
if(level == 1){
return 1;
}else{
int combinations = possibleCombinations(tmpArr, level-1);
arrangeFunction.put(getStringForDigitsRemaining(tmpArr), combinations);
totalCombination += combinations;
}
}
}
return totalCombination;
}
/**
* Creating deep copy of 2 dimensional array
* #param arr
* #return
*/
private int[][] createCopy(int[][] arr){
int[][] newArr = new int[arr.length][arr[0].length];
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[0].length;j++){
newArr[i][j] = arr[i][j];
}
}
return newArr;
}
private void printRow(int[] row){
for(int i: row)
System.out.print(i);
}
private String getStringForDigitsRemaining(int[][] digitsRemaining){
StringBuilder sb = new StringBuilder();
for(int i=0;i<digitsRemaining.length;i++){
sb.append(digitsRemaining[i][0]);
sb.append(digitsRemaining[i][1]);
}
return sb.toString();
}
/**
* Calculates x choose y
* #param x
* #param y
*/
private int combination(int x, int y){
if(x>0 && y>0 && x>y)
return factorial(x)/(factorial(y)*factorial(x-y));
else
return 0;
}
private int factorial(int x){
if(x==0)
return 1;
return x*factorial(x-1);
}
private void printAllCombination(){
for(int[] arr: rowPerms){
for(int i: arr)
System.out.print(i);
System.out.println();
}
}
}

design a stack such that getMinimum( ) should be O(1)

This is an interview question.
You need to design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack.
For example:
case #1
5 ← TOP
1
4
6
2
When getMinimum() is called it should return 1, which is the minimum element in the stack.
case #2
stack.pop()
stack.pop()
Note: Both 5 and 1 are popped out of the stack.
So after this, the stack looks like
4 ← TOP
6
2
When getMinimum() is called it should return 2 which is the minimum in the stack.
Constraints:
getMinimum should return the minimum value in O(1)
Space constraint also has to be considered while designing it and if you use extra space, it should be of constant space.
EDIT: This fails the "constant space" constraint - it basically doubles the space required. I very much doubt that there's a solution which doesn't do that though, without wrecking the runtime complexity somewhere (e.g. making push/pop O(n)). Note that this doesn't change the complexity of the space required, e.g. if you've got a stack with O(n) space requirements, this will still be O(n) just with a different constant factor.
Non-constant-space solution
Keep a "duplicate" stack of "minimum of all values lower in the stack". When you pop the main stack, pop the min stack too. When you push the main stack, push either the new element or the current min, whichever is lower. getMinimum() is then implemented as just minStack.peek().
So using your example, we'd have:
Real stack Min stack
5 --> TOP 1
1 1
4 2
6 2
2 2
After popping twice you get:
Real stack Min stack
4 2
6 2
2 2
Please let me know if this isn't enough information. It's simple when you grok it, but it might take a bit of head-scratching at first :)
(The downside of course is that it doubles the space requirement. Execution time doesn't suffer significantly though - i.e. it's still the same complexity.)
EDIT: There's a variation which is slightly more fiddly, but has better space in general. We still have the min stack, but we only pop from it when the value we pop from the main stack is equal to the one on the min stack. We only push to the min stack when the value being pushed onto the main stack is less than or equal to the current min value. This allows duplicate min values. getMinimum() is still just a peek operation. For example, taking the original version and pushing 1 again, we'd get:
Real stack Min stack
1 --> TOP 1
5 1
1 2
4
6
2
Popping from the above pops from both stacks because 1 == 1, leaving:
Real stack Min stack
5 --> TOP 1
1 2
4
6
2
Popping again only pops from the main stack, because 5 > 1:
Real stack Min stack
1 1
4 2
6
2
Popping again pops both stacks because 1 == 1:
Real stack Min stack
4 2
6
2
This ends up with the same worst case space complexity (double the original stack) but much better space usage if we rarely get a "new minimum or equal".
EDIT: Here's an implementation of Pete's evil scheme. I haven't tested it thoroughly, but I think it's okay :)
using System.Collections.Generic;
public class FastMinStack<T>
{
private readonly Stack<T> stack = new Stack<T>();
// Could pass this in to the constructor
private readonly IComparer<T> comparer = Comparer<T>.Default;
private T currentMin;
public T Minimum
{
get { return currentMin; }
}
public void Push(T element)
{
if (stack.Count == 0 ||
comparer.Compare(element, currentMin) <= 0)
{
stack.Push(currentMin);
stack.Push(element);
currentMin = element;
}
else
{
stack.Push(element);
}
}
public T Pop()
{
T ret = stack.Pop();
if (comparer.Compare(ret, currentMin) == 0)
{
currentMin = stack.Pop();
}
return ret;
}
}
Add a field to hold the minimum value and update it during Pop() and Push(). That way getMinimum() will be O(1), but Pop() and Push() will have to do a little more work.
If minimum value is popped, Pop() will be O(n), otherwise they will still both be O(1). When resizing Push() becomes O(n) as per the Stack implementation.
Here's a quick implementation
public sealed class MinStack {
private int MinimumValue;
private readonly Stack<int> Stack = new Stack<int>();
public int GetMinimum() {
if (IsEmpty) {
throw new InvalidOperationException("Stack is empty");
}
return MinimumValue;
}
public int Pop() {
var value = Stack.Pop();
if (value == MinimumValue) {
MinimumValue = Stack.Min();
}
return value;
}
public void Push(int value) {
if (IsEmpty || value < MinimumValue) {
MinimumValue = value;
}
Stack.Push(value);
}
private bool IsEmpty { get { return Stack.Count() == 0; } }
}
public class StackWithMin {
int min;
int size;
int[] data = new int[1024];
public void push ( int val ) {
if ( size == 0 ) {
data[size] = val;
min = val;
} else if ( val < min) {
data[size] = 2 * val - min;
min = val;
assert (data[size] < min);
} else {
data[size] = val;
}
++size;
// check size and grow array
}
public int getMin () {
return min;
}
public int pop () {
--size;
int val = data[size];
if ( ( size > 0 ) && ( val < min ) ) {
int prevMin = min;
min += min - val;
return prevMin;
} else {
return val;
}
}
public boolean isEmpty () {
return size == 0;
}
public static void main (String...args) {
StackWithMin stack = new StackWithMin();
for ( String arg: args )
stack.push( Integer.parseInt( arg ) );
while ( ! stack.isEmpty() ) {
int min = stack.getMin();
int val = stack.pop();
System.out.println( val + " " + min );
}
System.out.println();
}
}
It stores the current minimum explicitly, and if the minimum changes, instead of pushing the value, it pushes a value the same difference the other side of the new minimum ( if min = 7 and you push 5, it pushes 3 instead ( 5-|7-5| = 3) and sets min to 5; if you then pop 3 when min is 5 it sees that the popped value is less than min, so reverses the procedure to get 7 for the new min, then returns the previous min). As any value which doesn't cause a change the current minimum is greater than the current minimum, you have something that can be used to differentiate between values which change the minimum and ones which don't.
In languages which use fixed size integers, you're borrowing a bit of space from the representation of the values, so it may underflow and the assert will fail. But otherwise, it's constant extra space and all operations are still O(1).
Stacks which are based instead on linked lists have other places you can borrow a bit from, for example in C the least significant bit of the next pointer, or in Java the type of the objects in the linked list. For Java this does mean there's more space used compared to a contiguous stack, as you have the object overhead per link:
public class LinkedStackWithMin {
private static class Link {
final int value;
final Link next;
Link ( int value, Link next ) {
this.value = value;
this.next = next;
}
int pop ( LinkedStackWithMin stack ) {
stack.top = next;
return value;
}
}
private static class MinLink extends Link {
MinLink ( int value, Link next ) {
super( value, next );
}
int pop ( LinkedStackWithMin stack ) {
stack.top = next;
int prevMin = stack.min;
stack.min = value;
return prevMin;
}
}
Link top;
int min;
public LinkedStackWithMin () {
}
public void push ( int val ) {
if ( ( top == null ) || ( val < min ) ) {
top = new MinLink(min, top);
min = val;
} else {
top = new Link(val, top);
}
}
public int pop () {
return top.pop(this);
}
public int getMin () {
return min;
}
public boolean isEmpty () {
return top == null;
}
In C, the overhead isn't there, and you can borrow the lsb of the next pointer:
typedef struct _stack_link stack_with_min;
typedef struct _stack_link stack_link;
struct _stack_link {
size_t next;
int value;
};
stack_link* get_next ( stack_link* link )
{
return ( stack_link * )( link -> next & ~ ( size_t ) 1 );
}
bool is_min ( stack_link* link )
{
return ( link -> next & 1 ) ! = 0;
}
void push ( stack_with_min* stack, int value )
{
stack_link *link = malloc ( sizeof( stack_link ) );
link -> next = ( size_t ) stack -> next;
if ( (stack -> next == 0) || ( value == stack -> value ) ) {
link -> value = stack -> value;
link -> next |= 1; // mark as min
} else {
link -> value = value;
}
stack -> next = link;
}
etc.;
However, none of these are truly O(1). They don't require any more space in practice, because they exploit holes in the representations of numbers, objects or pointers in these languages. But a theoretical machine which used a more compact representation would require an extra bit to be added to that representation in each case.
I found a solution that satisfies all the constraints mentioned (constant time operations) and constant extra space.
The idea is to store the difference between min value and the input number, and update the min value if it is no longer the minimum.
The code is as follows:
public class MinStack {
long min;
Stack<Long> stack;
public MinStack(){
stack = new Stack<>();
}
public void push(int x) {
if (stack.isEmpty()) {
stack.push(0L);
min = x;
} else {
stack.push(x - min); //Could be negative if min value needs to change
if (x < min) min = x;
}
}
public int pop() {
if (stack.isEmpty()) return;
long pop = stack.pop();
if (pop < 0) {
long ret = min
min = min - pop; //If negative, increase the min value
return (int)ret;
}
return (int)(pop + min);
}
public int top() {
long top = stack.peek();
if (top < 0) {
return (int)min;
} else {
return (int)(top + min);
}
}
public int getMin() {
return (int)min;
}
}
Credit goes to: https://leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack
Well, what are the runtime constraints of push and pop? If they are not required to be constant, then just calculate the minimum value in those two operations (making them O(n)). Otherwise, I don't see how this can be done with constant additional space.
Let's assume the stack which we will be working on is this :
6 , minvalue=2
2 , minvalue=2
5 , minvalue=3
3 , minvalue=3
9 , minvalue=7
7 , minvalue=7
8 , minvalue=8
In the above representation the stack is only built by left value's the right value's [minvalue] is written only for illustration purpose which will be stored in one variable.
The actual problem is when the value which is the minimum value gets removed: At that point how can we know what is the next minimum element without iterating over the stack.
Like for example in our stack when 6 gets popped we know that, this is not the minimum element because the minimum element is 2, so we can safely remove this without updating our min value.
But when we pop 2, we can see that the minimum value is 2 right now and if this gets popped out then we need to update the minimum value to 3.
Point1:
Now if you observe carefully we need to generate minvalue=3 from this particular state [2 , minvalue=2].
Or if you go deeper in the stack we need to generate minvalue=7 from this particular state [3 , minvalue=3]
or if you go deeper still in the stack then we need to generate minvalue=8 from this particular state [7 , minvalue=7]
Did you notice something in common in all of the above three cases? The value which we need to generate depends upon two variable which are both equal. Correct.
Why is this happening because when we push some element smaller then the current minvalue, then we basically push that element in the stack and updated the same number in minvalue also.
Point2:
So we are basically storing duplicate of the same number once in stack and once in minvalue variable.
We need to focus on avoiding this duplication and store something useful data in the stack or the minvalue to generate the previous minimum as shown in CASES above.
Let's focus on what should we store in stack when the value to store in push is less than the minimum value.
Let's name this variable y, so now our stack will look something like this:
6 , minvalue=2
y1 , minvalue=2
5 , minvalue=3
y2 , minvalue=3
9 , minvalue=7
y3 , minvalue=7
8 , minvalue=8
I have renamed them as y1,y2,y3 to avoid confusion that all of them will have same value.
Point3:
Now let's try to find some constraint's over y1, y2 and y3.
Do you remember when exactly we need to update the minvalue while doing pop(), only when we have popped the element which is equal to the minvalue.
If we pop something greater than the minvalue then we don't have to update minvalue.
So to trigger the update of minvalue, y1,y2&y3 should be smaller than there corresponding minvalue. [We are avoiding equality to avoid duplicate[Point2]]
so the constrain is [ y < minValue ].
Now let's come back to populate y, we need to generate some value and put y at the time of push, remember.
Let's take the value which is coming for push to be x which is less that the prevMinvalue, and the value which we will actually push in stack to be y.
So one thing is obvious that the newMinValue=x, and y < newMinvalue.
Now we need to calculate y(remember y can be any number which is less than newMinValue(x) so we need to find some number which can fulfil our constraint) with the help of prevMinvalue and x(newMinvalue).
Let's do the math:
x < prevMinvalue [Given]
x - prevMinvalue < 0
x - prevMinValue + x < 0 + x [Add x on both side]
2*x - prevMinValue < x
this is the y which we were looking for less than x(newMinValue).
y = 2*x - prevMinValue. 'or' y = 2*newMinValue - prevMinValue 'or' y = 2*curMinValue - prevMinValue [taking curMinValue=newMinValue].
So at the time of pushing x if it is less than prevMinvalue then we push y[2*x-prevMinValue] and update newMinValue = x .
And at the time of pop if the stack contains something less than the minValue then that's our trigger to update the minValue.
We have to calculate prevMinValue from the curMinValue and y.
  y = 2*curMinValue - prevMinValue [Proved]
  prevMinValue = 2*curMinvalue - y .
2*curMinValue - y is the number which we need to update now to the prevMinValue.
Code for the same logic is shared below with O(1) time and O(1) space complexity.
// C++ program to implement a stack that supports
// getMinimum() in O(1) time and O(1) extra space.
#include <bits/stdc++.h>
using namespace std;
// A user defined stack that supports getMin() in
// addition to push() and pop()
struct MyStack
{
stack<int> s;
int minEle;
// Prints minimum element of MyStack
void getMin()
{
if (s.empty())
cout << "Stack is empty\n";
// variable minEle stores the minimum element
// in the stack.
else
cout <<"Minimum Element in the stack is: "
<< minEle << "\n";
}
// Prints top element of MyStack
void peek()
{
if (s.empty())
{
cout << "Stack is empty ";
return;
}
int t = s.top(); // Top element.
cout << "Top Most Element is: ";
// If t < minEle means minEle stores
// value of t.
(t < minEle)? cout << minEle: cout << t;
}
// Remove the top element from MyStack
void pop()
{
if (s.empty())
{
cout << "Stack is empty\n";
return;
}
cout << "Top Most Element Removed: ";
int t = s.top();
s.pop();
// Minimum will change as the minimum element
// of the stack is being removed.
if (t < minEle)
{
cout << minEle << "\n";
minEle = 2*minEle - t;
}
else
cout << t << "\n";
}
// Removes top element from MyStack
void push(int x)
{
// Insert new number into the stack
if (s.empty())
{
minEle = x;
s.push(x);
cout << "Number Inserted: " << x << "\n";
return;
}
// If new number is less than minEle
if (x < minEle)
{
s.push(2*x - minEle);
minEle = x;
}
else
s.push(x);
cout << "Number Inserted: " << x << "\n";
}
};
// Driver Code
int main()
{
MyStack s;
s.push(3);
s.push(5);
s.getMin();
s.push(2);
s.push(1);
s.getMin();
s.pop();
s.getMin();
s.pop();
s.peek();
return 0;
}
We can do this in O(n) time and O(1) space complexity, like so:
class MinStackOptimized:
def __init__(self):
self.stack = []
self.min = None
def push(self, x):
if not self.stack:
# stack is empty therefore directly add
self.stack.append(x)
self.min = x
else:
"""
Directly add (x-self.min) to the stack. This also ensures anytime we have a
negative number on the stack is when x was less than existing minimum
recorded thus far.
"""
self.stack.append(x-self.min)
if x < self.min:
# Update x to new min
self.min = x
def pop(self):
x = self.stack.pop()
if x < 0:
"""
if popped element was negative therefore this was the minimum
element, whose actual value is in self.min but stored value is what
contributes to get the next min. (this is one of the trick we use to ensure
we are able to get old minimum once current minimum gets popped proof is given
below in pop method), value stored during push was:
(x - self.old_min) and self.min = x therefore we need to backtrack
these steps self.min(current) - stack_value(x) actually implies to
x (self.min) - (x - self.old_min)
which therefore gives old_min back and therefore can now be set
back as current self.min.
"""
self.min = self.min - x
def top(self):
x = self.stack[-1]
if x < 0:
"""
As discussed above anytime there is a negative value on stack, this
is the min value so far and therefore actual value is in self.min,
current stack value is just for getting the next min at the time
this gets popped.
"""
return self.min
else:
"""
if top element of the stack was positive then it's simple, it was
not the minimum at the time of pushing it and therefore what we did
was x(actual) - self.min(min element at current stage) let's say `y`
therefore we just need to reverse the process to get the actual
value. Therefore self.min + y, which would translate to
self.min + x(actual) - self.min, thereby giving x(actual) back
as desired.
"""
return x + self.min
def getMin(self):
# Always self.min variable holds the minimum so for so easy peezy.
return self.min
Here is my version of implementation.
struct MyStack {
int element;
int *CurrentMiniAddress;
};
void Push(int value)
{
// Create you structure and populate the value
MyStack S = new MyStack();
S->element = value;
if(Stack.Empty())
{
// Since the stack is empty, point CurrentMiniAddress to itself
S->CurrentMiniAddress = S;
}
else
{
// Stack is not empty
// Retrieve the top element. No Pop()
MyStack *TopElement = Stack.Top();
// Remember Always the TOP element points to the
// minimum element in ths whole stack
if (S->element CurrentMiniAddress->element)
{
// If the current value is the minimum in the whole stack
// then S points to itself
S->CurrentMiniAddress = S;
}
else
{
// So this is not the minimum in the whole stack
// No worries, TOP is holding the minimum element
S->CurrentMiniAddress = TopElement->CurrentMiniAddress;
}
}
Stack.Add(S);
}
void Pop()
{
if(!Stack.Empty())
{
Stack.Pop();
}
}
int GetMinimum(Stack &stack)
{
if(!stack.Empty())
{
MyStack *Top = stack.top();
// Top always points to the minimumx
return Top->CurrentMiniAddress->element;
}
}
Here is my Code which runs with O(1). The previous code which I posted had problem when the minimum element gets popped. I modified my code. This one uses another Stack that maintains minimum element present in stack above the current pushed element.
class StackDemo
{
int[] stk = new int[100];
int top;
public StackDemo()
{
top = -1;
}
public void Push(int value)
{
if (top == 100)
Console.WriteLine("Stack Overflow");
else
stk[++top] = value;
}
public bool IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
public int Pop()
{
if (IsEmpty())
{
Console.WriteLine("Stack Underflow");
return 0;
}
else
return stk[top--];
}
public void Display()
{
for (int i = top; i >= 0; i--)
Console.WriteLine(stk[i]);
}
}
class MinStack : StackDemo
{
int top;
int[] stack = new int[100];
StackDemo s1; int min;
public MinStack()
{
top = -1;
s1 = new StackDemo();
}
public void PushElement(int value)
{
s1.Push(value);
if (top == 100)
Console.WriteLine("Stack Overflow");
if (top == -1)
{
stack[++top] = value;
stack[++top] = value;
}
else
{
// stack[++top]=value;
int ele = PopElement();
stack[++top] = ele;
int a = MininmumElement(min, value);
stack[++top] = min;
stack[++top] = value;
stack[++top] = a;
}
}
public int PopElement()
{
if (top == -1)
return 1000;
else
{
min = stack[top--];
return stack[top--];
}
}
public int PopfromStack()
{
if (top == -1)
return 1000;
else
{
s1.Pop();
return PopElement();
}
}
public int MininmumElement(int a,int b)
{
if (a > b)
return b;
else
return a;
}
public int StackTop()
{
return stack[top];
}
public void DisplayMinStack()
{
for (int i = top; i >= 0; i--)
Console.WriteLine(stack[i]);
}
}
class Program
{
static void Main(string[] args)
{
MinStack ms = new MinStack();
ms.PushElement(15);
ms.PushElement(2);
ms.PushElement(1);
ms.PushElement(13);
ms.PushElement(5);
ms.PushElement(21);
Console.WriteLine("Min Stack");
ms.DisplayMinStack();
Console.WriteLine("Minimum Element:"+ms.StackTop());
ms.PopfromStack();
ms.PopfromStack();
ms.PopfromStack();
ms.PopfromStack();
Console.WriteLine("Min Stack");
ms.DisplayMinStack();
Console.WriteLine("Minimum Element:" + ms.StackTop());
Thread.Sleep(1000000);
}
}
I used a different kind of stack. Here is the implementation.
//
// main.cpp
// Eighth
//
// Created by chaitanya on 4/11/13.
// Copyright (c) 2013 cbilgika. All rights reserved.
//
#include <iostream>
#include <limits>
using namespace std;
struct stack
{
int num;
int minnum;
}a[100];
void push(int n,int m,int &top)
{
top++;
if (top>=100) {
cout<<"Stack Full";
cout<<endl;
}
else{
a[top].num = n;
a[top].minnum = m;
}
}
void pop(int &top)
{
if (top<0) {
cout<<"Stack Empty";
cout<<endl;
}
else{
top--;
}
}
void print(int &top)
{
cout<<"Stack: "<<endl;
for (int j = 0; j<=top ; j++) {
cout<<"("<<a[j].num<<","<<a[j].minnum<<")"<<endl;
}
}
void get_min(int &top)
{
if (top < 0)
{
cout<<"Empty Stack";
}
else{
cout<<"Minimum element is: "<<a[top].minnum;
}
cout<<endl;
}
int main()
{
int top = -1,min = numeric_limits<int>::min(),num;
cout<<"Enter the list to push (-1 to stop): ";
cin>>num;
while (num!=-1) {
if (top == -1) {
min = num;
push(num, min, top);
}
else{
if (num < min) {
min = num;
}
push(num, min, top);
}
cin>>num;
}
print(top);
get_min(top);
return 0;
}
Output:
Enter the list to push (-1 to stop): 5
1
4
6
2
-1
Stack:
(5,5)
(1,1)
(4,1)
(6,1)
(2,1)
Minimum element is: 1
Try it. I think it answers the question. The second element of every pair gives the minimum value seen when that element was inserted.
I am posting the complete code here to find min and max in a given stack.
Time complexity will be O(1)..
package com.java.util.collection.advance.datastructure;
/**
*
* #author vsinha
*
*/
public abstract interface Stack<E> {
/**
* Placing a data item on the top of the stack is called pushing it
* #param element
*
*/
public abstract void push(E element);
/**
* Removing it from the top of the stack is called popping it
* #return the top element
*/
public abstract E pop();
/**
* Get it top element from the stack and it
* but the item is not removed from the stack, which remains unchanged
* #return the top element
*/
public abstract E peek();
/**
* Get the current size of the stack.
* #return
*/
public abstract int size();
/**
* Check whether stack is empty of not.
* #return true if stack is empty, false if stack is not empty
*/
public abstract boolean empty();
}
package com.java.util.collection.advance.datastructure;
#SuppressWarnings("hiding")
public abstract interface MinMaxStack<Integer> extends Stack<Integer> {
public abstract int min();
public abstract int max();
}
package com.java.util.collection.advance.datastructure;
import java.util.Arrays;
/**
*
* #author vsinha
*
* #param <E>
*/
public class MyStack<E> implements Stack<E> {
private E[] elements =null;
private int size = 0;
private int top = -1;
private final static int DEFAULT_INTIAL_CAPACITY = 10;
public MyStack(){
// If you don't specify the size of stack. By default, Stack size will be 10
this(DEFAULT_INTIAL_CAPACITY);
}
#SuppressWarnings("unchecked")
public MyStack(int intialCapacity){
if(intialCapacity <=0){
throw new IllegalArgumentException("initial capacity can't be negative or zero");
}
// Can't create generic type array
elements =(E[]) new Object[intialCapacity];
}
#Override
public void push(E element) {
ensureCapacity();
elements[++top] = element;
++size;
}
#Override
public E pop() {
E element = null;
if(!empty()) {
element=elements[top];
// Nullify the reference
elements[top] =null;
--top;
--size;
}
return element;
}
#Override
public E peek() {
E element = null;
if(!empty()) {
element=elements[top];
}
return element;
}
#Override
public int size() {
return size;
}
#Override
public boolean empty() {
return size == 0;
}
/**
* Increases the capacity of this <tt>Stack by double of its current length</tt> instance,
* if stack is full
*/
private void ensureCapacity() {
if(size != elements.length) {
// Don't do anything. Stack has space.
} else{
elements = Arrays.copyOf(elements, size *2);
}
}
#Override
public String toString() {
return "MyStack [elements=" + Arrays.toString(elements) + ", size="
+ size + ", top=" + top + "]";
}
}
package com.java.util.collection.advance.datastructure;
/**
* Time complexity will be O(1) to find min and max in a given stack.
* #author vsinha
*
*/
public class MinMaxStackFinder extends MyStack<Integer> implements MinMaxStack<Integer> {
private MyStack<Integer> minStack;
private MyStack<Integer> maxStack;
public MinMaxStackFinder (int intialCapacity){
super(intialCapacity);
minStack =new MyStack<Integer>();
maxStack =new MyStack<Integer>();
}
public void push(Integer element) {
// Current element is lesser or equal than min() value, Push the current element in min stack also.
if(!minStack.empty()) {
if(min() >= element) {
minStack.push(element);
}
} else{
minStack.push(element);
}
// Current element is greater or equal than max() value, Push the current element in max stack also.
if(!maxStack.empty()) {
if(max() <= element) {
maxStack.push(element);
}
} else{
maxStack.push(element);
}
super.push(element);
}
public Integer pop(){
Integer curr = super.pop();
if(curr !=null) {
if(min() == curr) {
minStack.pop();
}
if(max() == curr){
maxStack.pop();
}
}
return curr;
}
#Override
public int min() {
return minStack.peek();
}
#Override
public int max() {
return maxStack.peek();
}
#Override
public String toString() {
return super.toString()+"\nMinMaxStackFinder [minStack=" + minStack + "\n maxStack="
+ maxStack + "]" ;
}
}
// You can use the below program to execute it.
package com.java.util.collection.advance.datastructure;
import java.util.Random;
public class MinMaxStackFinderApp {
public static void main(String[] args) {
MinMaxStack<Integer> stack =new MinMaxStackFinder(10);
Random random =new Random();
for(int i =0; i< 10; i++){
stack.push(random.nextInt(100));
}
System.out.println(stack);
System.out.println("MAX :"+stack.max());
System.out.println("MIN :"+stack.min());
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println(stack);
System.out.println("MAX :"+stack.max());
System.out.println("MIN :"+stack.min());
}
}
Let me know if you are facing any issue
Thanks,
Vikash
class FastStack {
private static class StackNode {
private Integer data;
private StackNode nextMin;
public StackNode(Integer data) {
this.data = data;
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public StackNode getNextMin() {
return nextMin;
}
public void setNextMin(StackNode nextMin) {
this.nextMin = nextMin;
}
}
private LinkedList<StackNode> stack = new LinkedList<>();
private StackNode currentMin = null;
public void push(Integer item) {
StackNode node = new StackNode(item);
if (currentMin == null) {
currentMin = node;
node.setNextMin(null);
} else if (item < currentMin.getData()) {
StackNode oldMinNode = currentMin;
node.setNextMin(oldMinNode);
currentMin = node;
}
stack.addFirst(node);
}
public Integer pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
StackNode node = stack.peek();
if (currentMin == node) {
currentMin = node.getNextMin();
}
stack.removeFirst();
return node.getData();
}
public Integer getMinimum() {
if (stack.isEmpty()) {
throw new NoSuchElementException("Stack is empty");
}
return currentMin.getData();
}
}
Here is my Code which runs with O(1). Here I used vector pair which contain the value which pushed and also contain the minimum value up to this pushed value.
Here is my version of C++ implementation.
vector<pair<int,int> >A;
int sz=0; // to keep track of the size of vector
class MinStack
{
public:
MinStack()
{
A.clear();
sz=0;
}
void push(int x)
{
int mn=(sz==0)?x: min(A[sz-1].second,x); //find the minimum value upto this pushed value
A.push_back(make_pair(x,mn));
sz++; // increment the size
}
void pop()
{
if(sz==0) return;
A.pop_back(); // pop the last inserted element
sz--; // decrement size
}
int top()
{
if(sz==0) return -1; // if stack empty return -1
return A[sz-1].first; // return the top element
}
int getMin()
{
if(sz==0) return -1;
return A[sz-1].second; // return the minimum value at sz-1
}
};
**The task can be acheived by creating two stacks:**
import java.util.Stack;
/*
*
* Find min in stack using O(n) Space Complexity
*/
public class DeleteMinFromStack {
void createStack(Stack<Integer> primary, Stack<Integer> minStack, int[] arr) {
/* Create main Stack and in parallel create the stack which contains the minimum seen so far while creating main Stack */
primary.push(arr[0]);
minStack.push(arr[0]);
for (int i = 1; i < arr.length; i++) {
primary.push(arr[i]);
if (arr[i] <= minStack.peek())// Condition to check to push the value in minimum stack only when this urrent value is less than value seen at top of this stack */
minStack.push(arr[i]);
}
}
int findMin(Stack<Integer> secStack) {
return secStack.peek();
}
public static void main(String args[]) {
Stack<Integer> primaryStack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
DeleteMinFromStack deleteMinFromStack = new DeleteMinFromStack();
int[] arr = { 5, 5, 6, 8, 13, 1, 11, 6, 12 };
deleteMinFromStack.createStack(primaryStack, minStack, arr);
int mimElement = deleteMinFromStack.findMin(primaryStack, minStack);
/** This check for algorithm when the main Stack Shrinks by size say i as in loop below */
for (int i = 0; i < 2; i++) {
primaryStack.pop();
}
System.out.println(" Minimum element is " + mimElement);
}
}
/*
here in have tried to add for loop wherin the main tack can be shrinked/expaned so we can check the algorithm */
A practical implementation for finding minimum in a Stack of User Designed Object,
named: School
The Stack is going to store the Schools in Stack based on the rank assigned to a school in specific region, say, findMin() gives the School where we get the maximum number of applications for Admissions, which in turn is to be defined by the comparator which uses rank associated with the schools in previous season .
The Code for same is below:
package com.practical;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class CognitaStack {
public School findMin(Stack<School> stack, Stack<School> minStack) {
if (!stack.empty() && !minStack.isEmpty())
return (School) minStack.peek();
return null;
}
public School removeSchool(Stack<School> stack, Stack<School> minStack) {
if (stack.isEmpty())
return null;
School temp = stack.peek();
if (temp != null) {
// if(temp.compare(stack.peek(), minStack.peek())<0){
stack.pop();
minStack.pop();
// }
// stack.pop();
}
return stack.peek();
}
public static void main(String args[]) {
Stack<School> stack = new Stack<School>();
Stack<School> minStack = new Stack<School>();
List<School> lst = new LinkedList<School>();
School s1 = new School("Polam School", "London", 3);
School s2 = new School("AKELEY WOOD SENIOR SCHOOL", "BUCKINGHAM", 4);
School s3 = new School("QUINTON HOUSE SCHOOL", "NORTHAMPTON", 2);
School s4 = new School("OAKLEIGH HOUSE SCHOOL", " SWANSEA", 5);
School s5 = new School("OAKLEIGH-OAK HIGH SCHOOL", "Devon", 1);
School s6 = new School("BritishInter2", "Devon", 7);
lst.add(s1);
lst.add(s2);
lst.add(s3);
lst.add(s4);
lst.add(s5);
lst.add(s6);
Iterator<School> itr = lst.iterator();
while (itr.hasNext()) {
School temp = itr.next();
if ((minStack.isEmpty()) || (temp.compare(temp, minStack.peek()) < 0)) { // minStack.peek().equals(temp)
stack.push(temp);
minStack.push(temp);
} else {
minStack.push(minStack.peek());
stack.push(temp);
}
}
CognitaStack cogStack = new CognitaStack();
System.out.println(" Minimum in Stack is " + cogStack.findMin(stack, minStack).name);
cogStack.removeSchool(stack, minStack);
cogStack.removeSchool(stack, minStack);
System.out.println(" Minimum in Stack is "
+ ((cogStack.findMin(stack, minStack) != null) ? cogStack.findMin(stack, minStack).name : "Empty"));
}
}
Also the School Object is as follows:
package com.practical;
import java.util.Comparator;
public class School implements Comparator<School> {
String name;
String location;
int rank;
public School(String name, String location, int rank) {
super();
this.name = name;
this.location = location;
this.rank = rank;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + rank;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
School other = (School) obj;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (rank != other.rank)
return false;
return true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int compare(School o1, School o2) {
// TODO Auto-generated method stub
return o1.rank - o2.rank;
}
}
class SchoolComparator implements Comparator<School> {
public int compare(School o1, School o2) {
return o1.rank - o2.rank;
}
}
This Example covers the following:
1. Implementation of Stack for User defined Objects, here, School
2. Implementation for the hashcode() and equals() method using all fields of Objects to be compared
3. A practical implementation for the scenario where we rqeuire to get the Stack contains operation to be in order of O(1)
Here's the PHP implementation of what explained in Jon Skeet's answer as the slightly better space complexity implementation to get the maximum of stack in O(1).
<?php
/**
* An ordinary stack implementation.
*
* In real life we could just extend the built-in "SplStack" class.
*/
class BaseIntegerStack
{
/**
* Stack main storage.
*
* #var array
*/
private $storage = [];
// ------------------------------------------------------------------------
// Public API
// ------------------------------------------------------------------------
/**
* Pushes to stack.
*
* #param int $value New item.
*
* #return bool
*/
public function push($value)
{
return is_integer($value)
? (bool) array_push($this->storage, $value)
: false;
}
/**
* Pops an element off the stack.
*
* #return int
*/
public function pop()
{
return array_pop($this->storage);
}
/**
* See what's on top of the stack.
*
* #return int|bool
*/
public function top()
{
return empty($this->storage)
? false
: end($this->storage);
}
// ------------------------------------------------------------------------
// Magic methods
// ------------------------------------------------------------------------
/**
* String representation of the stack.
*
* #return string
*/
public function __toString()
{
return implode('|', $this->storage);
}
} // End of BaseIntegerStack class
/**
* The stack implementation with getMax() method in O(1).
*/
class Stack extends BaseIntegerStack
{
/**
* Internal stack to keep track of main stack max values.
*
* #var BaseIntegerStack
*/
private $maxStack;
/**
* Stack class constructor.
*
* Dependencies are injected.
*
* #param BaseIntegerStack $stack Internal stack.
*
* #return void
*/
public function __construct(BaseIntegerStack $stack)
{
$this->maxStack = $stack;
}
// ------------------------------------------------------------------------
// Public API
// ------------------------------------------------------------------------
/**
* Prepends an item into the stack maintaining max values.
*
* #param int $value New item to push to the stack.
*
* #return bool
*/
public function push($value)
{
if ($this->isNewMax($value)) {
$this->maxStack->push($value);
}
parent::push($value);
}
/**
* Pops an element off the stack maintaining max values.
*
* #return int
*/
public function pop()
{
$popped = parent::pop();
if ($popped == $this->maxStack->top()) {
$this->maxStack->pop();
}
return $popped;
}
/**
* Finds the maximum of stack in O(1).
*
* #return int
* #see push()
*/
public function getMax()
{
return $this->maxStack->top();
}
// ------------------------------------------------------------------------
// Internal helpers
// ------------------------------------------------------------------------
/**
* Checks that passing value is a new stack max or not.
*
* #param int $new New integer to check.
*
* #return boolean
*/
private function isNewMax($new)
{
return empty($this->maxStack) OR $new > $this->maxStack->top();
}
} // End of Stack class
// ------------------------------------------------------------------------
// Stack Consumption and Test
// ------------------------------------------------------------------------
$stack = new Stack(
new BaseIntegerStack
);
$stack->push(9);
$stack->push(4);
$stack->push(237);
$stack->push(5);
$stack->push(556);
$stack->push(15);
print "Stack: $stack\n";
print "Max: {$stack->getMax()}\n\n";
print "Pop: {$stack->pop()}\n";
print "Pop: {$stack->pop()}\n\n";
print "Stack: $stack\n";
print "Max: {$stack->getMax()}\n\n";
print "Pop: {$stack->pop()}\n";
print "Pop: {$stack->pop()}\n\n";
print "Stack: $stack\n";
print "Max: {$stack->getMax()}\n";
// Here's the sample output:
//
// Stack: 9|4|237|5|556|15
// Max: 556
//
// Pop: 15
// Pop: 556
//
// Stack: 9|4|237|5
// Max: 237
//
// Pop: 5
// Pop: 237
//
// Stack: 9|4
// Max: 9
Here is the C++ implementation of Jon Skeets Answer.
It might not be the most optimal way of implementing it, but it does exactly what it's supposed to.
class Stack {
private:
struct stack_node {
int val;
stack_node *next;
};
stack_node *top;
stack_node *min_top;
public:
Stack() {
top = nullptr;
min_top = nullptr;
}
void push(int num) {
stack_node *new_node = nullptr;
new_node = new stack_node;
new_node->val = num;
if (is_empty()) {
top = new_node;
new_node->next = nullptr;
min_top = new_node;
new_node->next = nullptr;
} else {
new_node->next = top;
top = new_node;
if (new_node->val <= min_top->val) {
new_node->next = min_top;
min_top = new_node;
}
}
}
void pop(int &num) {
stack_node *tmp_node = nullptr;
stack_node *min_tmp = nullptr;
if (is_empty()) {
std::cout << "It's empty\n";
} else {
num = top->val;
if (top->val == min_top->val) {
min_tmp = min_top->next;
delete min_top;
min_top = min_tmp;
}
tmp_node = top->next;
delete top;
top = tmp_node;
}
}
bool is_empty() const {
return !top;
}
void get_min(int &item) {
item = min_top->val;
}
};
And here is the driver for the class
int main() {
int pop, min_el;
Stack my_stack;
my_stack.push(4);
my_stack.push(6);
my_stack.push(88);
my_stack.push(1);
my_stack.push(234);
my_stack.push(2);
my_stack.get_min(min_el);
cout << "Min: " << min_el << endl;
my_stack.pop(pop);
cout << "Popped stock element: " << pop << endl;
my_stack.pop(pop);
cout << "Popped stock element: " << pop << endl;
my_stack.pop(pop);
cout << "Popped stock element: " << pop << endl;
my_stack.get_min(min_el);
cout << "Min: " << min_el << endl;
return 0;
}
Output:
Min: 1
Popped stock element: 2
Popped stock element: 234
Popped stock element: 1
Min: 4
You could extend your original stack class and just add the min tracking to it. Let the original parent class handle everything else as usual.
public class StackWithMin extends Stack<Integer> {
private Stack<Integer> min;
public StackWithMin() {
min = new Stack<>();
}
public void push(int num) {
if (super.isEmpty()) {
min.push(num);
} else if (num <= min.peek()) {
min.push(num);
}
super.push(num);
}
public int min() {
return min.peek();
}
public Integer pop() {
if (super.peek() == min.peek()) {
min.pop();
}
return super.pop();
}
}
I think you can simply use a LinkedList in your stack implementation.
First time you push a value, you put this value as the linkedlist head.
then each time you push a value, if the new value < head.data, make a prepand operation ( which means the head becomes the new value )
if not, then make an append operation.
When you make a pop(), you check if min == linkedlist.head.data, if yes, then head=head.next;
Here is my code.
public class Stack {
int[] elements;
int top;
Linkedlists min;
public Stack(int n) {
elements = new int[n];
top = 0;
min = new Linkedlists();
}
public void realloc(int n) {
int[] tab = new int[n];
for (int i = 0; i < top; i++) {
tab[i] = elements[i];
}
elements = tab;
}
public void push(int x) {
if (top == elements.length) {
realloc(elements.length * 2);
}
if (top == 0) {
min.pre(x);
} else if (x < min.head.data) {
min.pre(x);
} else {
min.app(x);
}
elements[top++] = x;
}
public int pop() {
int x = elements[--top];
if (top == 0) {
}
if (this.getMin() == x) {
min.head = min.head.next;
}
elements[top] = 0;
if (4 * top < elements.length) {
realloc((elements.length + 1) / 2);
}
return x;
}
public void display() {
for (Object x : elements) {
System.out.print(x + " ");
}
}
public int getMin() {
if (top == 0) {
return 0;
}
return this.min.head.data;
}
public static void main(String[] args) {
Stack stack = new Stack(4);
stack.push(2);
stack.push(3);
stack.push(1);
stack.push(4);
stack.push(5);
stack.pop();
stack.pop();
stack.pop();
stack.push(1);
stack.pop();
stack.pop();
stack.pop();
stack.push(2);
System.out.println(stack.getMin());
stack.display();
}
}
Here is my solution in java using liked list.
class Stack{
int min;
Node top;
static class Node{
private int data;
private Node next;
private int min;
Node(int data, int min){
this.data = data;
this.min = min;
this.next = null;
}
}
void push(int data){
Node temp;
if(top == null){
temp = new Node(data,data);
top = temp;
top.min = data;
}
if(top.min > data){
temp = new Node(data,data);
temp.next = top;
top = temp;
} else {
temp = new Node(data, top.min);
temp.next = top;
top = temp;
}
}
void pop(){
if(top != null){
top = top.next;
}
}
int min(){
return top.min;
}
}
public class MinStack<E>{
private final LinkedList<E> mainStack = new LinkedList<E>();
private final LinkedList<E> minStack = new LinkedList<E>();
private final Comparator<E> comparator;
public MinStack(Comparator<E> comparator)
{
this.comparator = comparator;
}
/**
* Pushes an element onto the stack.
*
*
* #param e the element to push
*/
public void push(E e) {
mainStack.push(e);
if(minStack.isEmpty())
{
minStack.push(e);
}
else if(comparator.compare(e, minStack.peek())<=0)
{
minStack.push(e);
}
else
{
minStack.push(minStack.peek());
}
}
/**
* Pops an element from the stack.
*
*
* #throws NoSuchElementException if this stack is empty
*/
public E pop() {
minStack.pop();
return mainStack.pop();
}
/**
* Returns but not remove smallest element from the stack. Return null if stack is empty.
*
*/
public E getMinimum()
{
return minStack.peek();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Main stack{");
for (E e : mainStack) {
sb.append(e.toString()).append(",");
}
sb.append("}");
sb.append(" Min stack{");
for (E e : minStack) {
sb.append(e.toString()).append(",");
}
sb.append("}");
sb.append(" Minimum = ").append(getMinimum());
return sb.toString();
}
public static void main(String[] args) {
MinStack<Integer> st = new MinStack<Integer>(Comparators.INTEGERS);
st.push(2);
Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
System.out.println(st);
st.push(6);
Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
System.out.println(st);
st.push(4);
Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
System.out.println(st);
st.push(1);
Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
System.out.println(st);
st.push(5);
Assert.assertTrue("1 is min in stack {2,6,4,1,5}", st.getMinimum().equals(1));
System.out.println(st);
st.pop();
Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
System.out.println(st);
st.pop();
Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
System.out.println(st);
st.pop();
Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
System.out.println(st);
st.pop();
Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
System.out.println(st);
st.pop();
Assert.assertTrue("null is min in stack {}", st.getMinimum()==null);
System.out.println(st);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Solution
{
public class MinStack
{
public MinStack()
{
MainStack=new Stack<int>();
Min=new Stack<int>();
}
static Stack<int> MainStack;
static Stack<int> Min;
public void Push(int item)
{
MainStack.Push(item);
if(Min.Count==0 || item<Min.Peek())
Min.Push(item);
}
public void Pop()
{
if(Min.Peek()==MainStack.Peek())
Min.Pop();
MainStack.Pop();
}
public int Peek()
{
return MainStack.Peek();
}
public int GetMin()
{
if(Min.Count==0)
throw new System.InvalidOperationException("Stack Empty");
return Min.Peek();
}
}
}
Saw a brilliant solution here:
https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/
Bellow is the python code I wrote by following the algorithm:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class MinStack:
def __init__(self):
self.head = None
self.min = float('inf')
# #param x, an integer
def push(self, x):
if self.head == None:
self.head = Node(x)
self.min = x
else:
if x >= self.min:
n = Node(x)
n.next = self.head
self.head = n
else:
v = 2 * x - self.min
n = Node(v)
n.next = self.head
self.head = n
self.min = x
# #return nothing
def pop(self):
if self.head:
if self.head.value < self.min:
self.min = self.min * 2 - self.head.value
self.head = self.head.next
# #return an integer
def top(self):
if self.head:
if self.head.value < self.min:
self.min = self.min * 2 - self.head.value
return self.min
else:
return self.head.value
else:
return -1
# #return an integer
def getMin(self):
if self.head:
return self.min
else:
return -1
To getMin elements from Stack. We have to use Two stack .i.e Stack s1 and Stack s2.
Initially, both stacks are empty, so add elements to both stacks
---------------------Recursively call Step 2 to 4-----------------------
if New element added to stack s1.Then pop elements from stack s2
compare new elments with s2. which one is smaller , push to s2.
pop from stack s2(which contains min element)
Code looks like:
package Stack;
import java.util.Stack;
public class getMin
{
Stack<Integer> s1= new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
void push(int x)
{
if(s1.isEmpty() || s2.isEmpty())
{
s1.push(x);
s2.push(x);
}
else
{
s1. push(x);
int y = (Integer) s2.pop();
s2.push(y);
if(x < y)
s2.push(x);
}
}
public Integer pop()
{
int x;
x=(Integer) s1.pop();
s2.pop();
return x;
}
public int getmin()
{
int x1;
x1= (Integer)s2.pop();
s2.push(x1);
return x1;
}
public static void main(String[] args) {
getMin s = new getMin();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.getmin());
s.push(1);
System.out.println(s.getmin());
}
}
I have better solution, with O(1) time and with no extra space, You need to push element as String as <original_value,minimum_value>.
For example find this stack of string.
|-1,-1 |
| 1,1 |
| 2,2 |
| 5,3 |
| 3,3 |
Now u can always find min value at current instance by just using peek and checking what is min value at the given instance. this is O(1) time without extra space
class MyStackImplementation{
private final int capacity = 4;
int min;
int arr[] = new int[capacity];
int top = -1;
public void push ( int val ) {
top++;
if(top <= capacity-1){
if(top == 0){
min = val;
arr[top] = val;
}
else if(val < min){
arr[top] = arr[top]+min;
min = arr[top]-min;
arr[top] = arr[top]-min;
}
else {
arr[top] = val;
}
System.out.println("element is pushed");
}
else System.out.println("stack is full");
}
public void pop () {
top--;
if(top > -1){
min = arr[top];
}
else {min=0; System.out.println("stack is under flow");}
}
public int min(){
return min;
}
public boolean isEmpty () {
return top == 0;
}
public static void main(String...s){
MyStackImplementation msi = new MyStackImplementation();
msi.push(1);
msi.push(4);
msi.push(2);
msi.push(10);
System.out.println(msi.min);
msi.pop();
msi.pop();
msi.pop();
msi.pop();
msi.pop();
System.out.println(msi.min);
}
}
I think only push operation suffers, is enough. My implementation includes a stack of nodes. Each node contain the data item and also the minimum on that moment. This minimum is updated each time a push operation is done.
Here are some points for understanding:
I implemented the stack using Linked List.
A pointer top always points to the last pushed item. When there is no item in that stack top is NULL.
When an item is pushed a new node is allocated which has a next pointer that points to the previous stack and top is updated to point to this new node.
Only difference with normal stack implementation is that during push it updates a member min for the new node.
Please have a look at code which is implemented in C++ for demonstration purpose.
/*
* Implementation of Stack that can give minimum in O(1) time all the time
* This solution uses same data structure for minimum variable, it could be implemented using pointers but that will be more space consuming
*/
#include <iostream>
using namespace std;
typedef struct stackLLNodeType stackLLNode;
struct stackLLNodeType {
int item;
int min;
stackLLNode *next;
};
class DynamicStack {
private:
int stackSize;
stackLLNode *top;
public:
DynamicStack();
~DynamicStack();
void push(int x);
int pop();
int getMin();
int size() { return stackSize; }
};
void pushOperation(DynamicStack& p_stackObj, int item);
void popOperation(DynamicStack& p_stackObj);
int main () {
DynamicStack stackObj;
pushOperation(stackObj, 3);
pushOperation(stackObj, 1);
pushOperation(stackObj, 2);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
pushOperation(stackObj, 4);
pushOperation(stackObj, 7);
pushOperation(stackObj, 6);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
popOperation(stackObj);
return 0;
}
DynamicStack::DynamicStack() {
// initialization
stackSize = 0;
top = NULL;
}
DynamicStack::~DynamicStack() {
stackLLNode* tmp;
// chain memory deallocation to avoid memory leak
while (top) {
tmp = top;
top = top->next;
delete tmp;
}
}
void DynamicStack::push(int x) {
// allocate memory for new node assign to top
if (top==NULL) {
top = new stackLLNode;
top->item = x;
top->next = NULL;
top->min = top->item;
}
else {
// allocation of memory
stackLLNode *tmp = new stackLLNode;
// assign the new item
tmp->item = x;
tmp->next = top;
// store the minimum so that it does not get lost after pop operation of later minimum
if (x < top->min)
tmp->min = x;
else
tmp->min = top->min;
// update top to new node
top = tmp;
}
stackSize++;
}
int DynamicStack::pop() {
// check if stack is empty
if (top == NULL)
return -1;
stackLLNode* tmp = top;
int curItem = top->item;
top = top->next;
delete tmp;
stackSize--;
return curItem;
}
int DynamicStack::getMin() {
if (top == NULL)
return -1;
return top->min;
}
void pushOperation(DynamicStack& p_stackObj, int item) {
cout<<"Just pushed: "<<item<<endl;
p_stackObj.push(item);
cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
}
void popOperation(DynamicStack& p_stackObj) {
int popItem = -1;
if ((popItem = p_stackObj.pop()) == -1 )
cout<<"Cannot pop. Stack is empty."<<endl;
else {
cout<<"Just popped: "<<popItem<<endl;
if (p_stackObj.getMin() == -1)
cout<<"No minimum. Stack is empty."<<endl;
else
cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
}
}
And the output of the program looks like this:
Just pushed: 3
Current stack min: 3
Current stack size: 1
Just pushed: 1
Current stack min: 1
Current stack size: 2
Just pushed: 2
Current stack min: 1
Current stack size: 3
Just popped: 2
Current stack min: 1
Current stack size: 2
Just popped: 1
Current stack min: 3
Current stack size: 1
Just popped: 3
No minimum. Stack is empty.
Current stack size: 0
Cannot pop. Stack is empty.
Just pushed: 4
Current stack min: 4
Current stack size: 1
Just pushed: 7
Current stack min: 4
Current stack size: 2
Just pushed: 6
Current stack min: 4
Current stack size: 3
Just popped: 6
Current stack min: 4
Current stack size: 2
Just popped: 7
Current stack min: 4
Current stack size: 1
Just popped: 4
No minimum. Stack is empty.
Current stack size: 0
Cannot pop. Stack is empty.
#include<stdio.h>
struct stack
{
int data;
int mindata;
}a[100];
void push(int *tos,int input)
{
if (*tos > 100)
{
printf("overflow");
return;
}
(*tos)++;
a[(*tos)].data=input;
if (0 == *tos)
a[*tos].mindata=input;
else if (a[*tos -1].mindata < input)
a[*tos].mindata=a[*tos -1].mindata;
else
a[*tos].mindata=input;
}
int pop(int * tos)
{
if (*tos <= -1)
{
printf("underflow");
return -1;
}
return(a[(*tos)--].data);
}
void display(int tos)
{
while (tos > -1)
{
printf("%d:%d\t",a[tos].data,a[tos].mindata);
tos--;
}
}
int min(int tos)
{
return(a[tos].mindata);
}
int main()
{
int tos=-1,x,choice;
while(1)
{
printf("press 1-push,2-pop,3-mindata,4-display,5-exit ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("enter data to push");
scanf("%d",&x);
push(&tos,x);
break;
case 2: printf("the poped out data=%d ",pop(&tos));
break;
case 3: printf("The min peeped data:%d",min(tos));
break;
case 4: printf("The elements of stack \n");
display(tos);
break;
default: exit(0);
}
}
I found this solution here
struct StackGetMin {
void push(int x) {
elements.push(x);
if (minStack.empty() || x <= minStack.top())
minStack.push(x);
}
bool pop() {
if (elements.empty()) return false;
if (elements.top() == minStack.top())
minStack.pop();
elements.pop();
return true;
}
bool getMin(int &min) {
if (minStack.empty()) {
return false;
} else {
min = minStack.top();
return true;
}
}
stack<int> elements;
stack<int> minStack;
};
struct Node {
let data: Int
init(_ d:Int){
data = d
}
}
struct Stack {
private var backingStore = [Node]()
private var minArray = [Int]()
mutating func push(n:Node) {
backingStore.append(n)
minArray.append(n.data)
minArray.sort(>)
minArray
}
mutating func pop() -> Node? {
if(backingStore.isEmpty){
return nil
}
let n = backingStore.removeLast()
var found = false
minArray = minArray.filter{
if (!found && $0 == n.data) {
found = true
return false
}
return true
}
return n
}
func min() -> Int? {
return minArray.last
}
}

Resources