Showing posts with label Stack-Queue. Show all posts
Showing posts with label Stack-Queue. Show all posts

Saturday, August 13, 2016

The Celebrity Problem

In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in minimum number of questions.

http://www.geeksforgeeks.org/the-celebrity-problem/

The Stock Span Problem

The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock’s price for all n days.
The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}
http://www.geeksforgeeks.org/the-stock-span-problem/

Friday, August 12, 2016

Find maximum of minimum for every window size in a given array

Given an integer array of size n, find the maximum of the minimum’s of every window size in the array. Note that window size varies from 1 to n.

Example:

Input:  arr[] = {10, 20, 30, 50, 10, 70, 30}
Output:         70, 30, 20, 10, 10, 10, 10

First element in output indicates maximum of minimums of all
windows of size 1.
Minimums of windows of size 1 are {10}, {20}, {30}, {50}, {10},
{70} and {30}.  Maximum of these minimums is 70

http://www.geeksforgeeks.org/find-the-maximum-of-minimums-for-every-window-size-in-a-given-array/

Design a stack with operations on middle element

How to implement a stack which will support following operations in O(1) time complexity?
1) push() which adds an element to the top of stack.
2) pop() which removes an element from top of stack.
3) findMiddle() which will return middle element of the stack.
4) deleteMiddle() which will delete the middle element.
Push and pop are standard stack operations.

http://www.geeksforgeeks.org/design-a-stack-with-find-middle-operation/

Check if a given array can represent Preorder Traversal of Binary Search Tree

Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n).

Input:  pre[] = {2, 4, 3}
Output: true
    2
     \
      4
     /
    3
Input:  pre[] = {2, 4, 1}
Output: false
http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/


Find the first circular tour that visits all petrol pumps

Suppose there is a circle. There are n petrol pumps on that circle. You are given two sets of data.

1. The amount of petrol that every petrol pump has.
2. Distance from that petrol pump to the next petrol pump.

Calculate the first point from where a truck will be able to complete the circle (The truck will stop at each petrol pump and it has infinite capacity). Expected time complexity is O(n). Assume for 1 litre petrol, the truck can go 1 unit of distance.

For example, let there be 4 petrol pumps with amount of petrol and distance to next petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The first point from where truck can make a circular tour is 2nd petrol pump. Output should be “start = 1″ (index of 2nd petrol pump).

http://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/


Saturday, August 6, 2016

Find the nearest smaller numbers on left side in an array

Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.

Examples:
Input:  arr[] = {1, 6, 4, 10, 2, 5} Output:         {_, 1, 1,  4, 1, 2}
First element ('1') has no element on left side. For 6,
there is only one smaller element on left side '1'.
For 10, there are three smaller elements on left side (1,
6 and 4), nearest among the three elements is 4.

Input: arr[] = {1, 3, 0, 2, 5}  Output:        {_, 1, _, 0, 2}
http://www.geeksforgeeks.org/find-the-nearest-smaller-numbers-on-left-side-in-an-array/

Friday, March 16, 2012

Thursday, March 15, 2012

Remove overlapping sets and Merge overlapping intervals

Question 1: Remove overlapping sets
You are given n variable length sets with each set like set1: [s1.....e1], set2:[s2.....e2] with the condition that the sets overlap (i.e. if you represent them on number line, they intersect). Now you have to remove the minimum number of sets from here so that the remaining sets are disjoint.

For example you have set S1, S2, S3 with S1 and S3 disjoint and S2 overlapping both S1 and S3 then we remove S2 to get the answer.
Strategy:
Assume all the sets are sorted.
Find the maximum value out of all the sets i.e., compare the last value in each set & find the maximum value.
Create a bitset with a size that of this maximum value.
Walk through the first set & for each value set the corresponding bit. i.e, if s1 = 6, then the 6th bit is set.
Pick the next set. Walk through it. If you find any bit is already set, for any value of this set, then that set needs to be removed.
Follow the same for all the remaining sets.

Question 2: Merge Overlapping Intervals
Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Let the intervals be represented as pairs of integers for simplicity.
For example, let the given set of intervals be {{1,3}, {2,4}, {5,7}, {6,8} }. The intervals {1,3} and {2,4} overlap with each other, so they should be merged and become {1, 4}. Similarly {5, 7} and {6, 8} should be merged and become {5, 8}
Strategy:
1. Sort the intervals based on increasing order of
    starting time.
2. Push the first interval on to a stack.
3. For each interval do the following
   a. If the current interval does not overlap with the stack
       top, push it.
   b. If the current interval overlaps with stack top and ending
       time of current interval is more than that of stack top,
       update stack top with the ending  time of current interval.
4. At the end stack contains the merged intervals.
http://www.geeksforgeeks.org/merging-intervals/

Sunday, March 11, 2012

Largest Area Rectangle in a Histogram

Find the maximum rectangle (in terms of area) under a histogram in linear time. I mean the area of largest rectangle that fits entirely in the Histogram.
Given:A histogram with integer heights and constant width 1. I want to maximize the rectangular area under a histogram. e.g.: 
 _
| |
| |_ 
|   |
|   |_
|     |  The answer for this would be 6, 3 * 2, using col1 and col2.
Method 1: Using Stack: O(n)
1) Create an empty stack. 2) Start from first bar, and do following for every bar ‘hist[i]’ where ‘i’ varies from 0 to n-1. ……a) If stack is empty or hist[i] is higher than the bar at top of stack, then push ‘i’ to stack. ……b) If this bar is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater. Let the removed bar be hist[tp]. Calculate area of rectangle with hist[tp] as smallest bar. For hist[tp], the ‘left index’ is previous (previous to tp) item in stack and ‘right index’ is ‘i’ (current index). 3) If the stack is not empty, then one by one remove all bars from stack and do step 2.b for every removed bar. Variation:
http://www.programcreek.com/2014/05/leetcode-maximal-rectangle-java/

C++ implementation

http://tech-queries.blogspot.in/2011/03/maximum-area-rectangle-in-histogram.html

Java implementation
http://www.programcreek.com/2014/05/leetcode-largest-rectangle-in-histogram-java/
Method 2: Using  Divide and Conquer : Range Minimum Query: O(nlogn)
http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/

Wednesday, February 15, 2012

Queue with getmax() operation

Implement a queue with following operations:
  • removeFirst - remove the first element
  • getFirst - get the value of first element
  • addLast - append the value to the end of queue.
  • getMax - get the maximum value of the queue.

Tuesday, January 3, 2012

Tower of Hanoi using Stacks

Design an algorithm using stacks.
We have to move 64 disks from one pole to another. But there are some rules about how this should be done, which are:
  1. You can move only one disk at a time.
  2. For temporary storage, a third pole may be used.
  3. You cannot place a disk of larger diameter on a disk of smaller diameter
Theory:
Recursive:
Iterative:

Maximum of all subarrays of size k

Maximum of all subarrays of size k (Added a O(n) method)
Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.
http://www.geeksforgeeks.org/maximum-of-all-subarrays-of-size-k/

Thursday, December 22, 2011

Push(),Pop(), and GetMin() elements at complexity O(1)

Design a stack. We want to push, pop, and also, retrieve the minimum element in constant time.

http://www.geeksforgeeks.org/design-and-implement-special-stack-data-structure/
http://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/

Method 1:2 stacks
A constant time minimum lookup can be achieved by using an extra stack. Let's call this stack 'min_stack'. This stack will always have the minimum value at the top.

Modify 'push' and 'pop' operations as follows:

push:
- If the element being pushed is less than the top element of 'min_stack' then push it on 'min_stack' as well.
- Else, push the top element of 'min_stack' again on 'min_stack'.

pop:
- Every time you pop an element from the original stack, pop from 'min_stack' as well.

Example:
Suppose, elements are pushed in the following order: 7 3 5 8 9 1 2

original_stack                min_stack
        2                                 1
        1                                 1
        9                                 3
        8                                 3
        5                                 3
        3                                 3
        7                                 7

You can see that at any stage, the 'min_stack' can be queried for the minimum element in the stack.


Method 2:Single Stack
PUSH : While inserting the element into stack we insert the element and also keep track of minimum element at every insert and also insert the minimum element. This doubles up the stack usage to 2n. where n is number of element. O(1).

POP : While extracting element out of the stack, we need to extract two elements one is the minimum element tracked so far and the actual element of the array. O(1)

FIND MIN:Single pop operation will be able to fetch the minimum element. O(1).

Saturday, December 17, 2011

Reverse a stack and a queue

Reverse a stack using standard stack operations like push(), pop(), isEmpty().

Strategy:

Even recursion will take extra space, but, the purpose of the question is to come up with a recursive implementation. First, we will implement a function "insertAtBottom()" which inserts an element at the bottom of the stack. And then we will use this function to implement "reverseStack()"

Algo:
- recursively empty the stack.
- add elements back using "insertAtBottom()"
 

Code:

void insertAtBottom(stack& s, int x)
{
    if(s.empty())
    {
        s.push(x);
        return;
    }

    int a = s.top();
    s.pop();
    insertAtBottom(s, x);
    s.push(a);
}

void reverseStack(stack& s)
{
    if(s.empty())
        return;

    int a = s.top();
    s.pop();
    reverseStack(s);
    insertAtBottom(s, a);
}

int main()
{
    stack s;

    s.push(5);
    s.push(4);
    s.push(2);
    s.push(7);
    s.push(9);

    //current stack: top - 9 7 2 4 5 - bottom
   
    reverseStack(s);

    //reversed stack: top - 5 4 2 7 9 - bottom
   
    while(!s.empty())
    {
        printf("%d ", s.top());
        s.pop();
    }
    printf("\n");

    return 1;
}

Reverse a queue in O(n).

Strategy:Using a stack
#include<iostream>

//add std library for stack and queue
#include<stack>
#include<queue>
using namespace std;

int main() {

    //define queue and stack ADT
    queue <int> Q;
    stack <int> st;

    //enqueue Q
    Q.push(1);
    Q.push(2);
    Q.push(3);
    Q.push(4);
    Q.push(5);
    Q.push(6);
    Q.push(7);
    Q.push(8);
    Q.push(9);
    Q.push(10);

    //dequeue Q & push elements to st
    while (!Q.empty()){
        st.push(Q.front());
        Q.pop();
    }

   //pop elements from st and enQueue again Q
    while (!st.empty()){
        Q.push(st.top());
        st.pop();
    }

    //finally print queue elements in reverse order
    while (!Q.empty()){
        cout << Q.front();
        Q.pop();
    }
    return 0;

}

Polish Notation: Conversion and Evaluation using Stacks

What do you mean by POLISH NOTATION of an arithmetic expression
1.How can we convert from one expression to another
2.How can we evaluate these expressions.

Expression Conversion:
http://quiz.geeksforgeeks.org/stack-set-2-infix-to-postfix/

Expression Evaluation:
Infix:
http://www.geeksforgeeks.org/expression-evaluation/
Postfix:
http://quiz.geeksforgeeks.org/stack-set-4-evaluation-postfix-expression/
Reverse Polish Notation:
http://www.programcreek.com/2012/12/leetcode-evaluate-reverse-polish-notation/

Useful Links:--
http://www.contrib.andrew.cmu.edu/~rrv/updated%20cracktheinterview/www.cracktheinterview.com/pages/19_12.html
http://www.dreamincode.net/forums/topic/37428-converting-and-evaluating-infix-postfix-and-prefix-expressions-in-c/
http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29


Stack with 2 Queues and Queue with 2 Stacks

Stack using 2 Queues.

http://www.geeksforgeeks.org/implement-stack-using-queue/
Strategy:
Version A:
  • push:
    • enqueue in queue1
  • pop:
    • while size of queue1 is bigger than 1, pipe dequeued items from queue1 into queue2
    • dequeue and return the last item of queue1, then switch the names of queue1 and queue2
Version B:
  • push:
    • enqueue in queue2
    • enqueue all items of queue1 in queue2, then switch the names of queue1 and queue2
  • pop:
    • deqeue from queue1
Queue using 2 STACKS.

Strategy:
A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways:

Method 1 (By making enQueue operation costly)
This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.
enQueue(q, x)
  1) While stack1 is not empty, push everything from satck1 to stack2.
  2) Push x to stack1 (assuming size of stacks is unlimited).
  3) Push everything back to stack1.

dnQueue(q)
  1) If stack1 is empty then error
  2) Pop an item from stack1 and return it
 
Method 2 (By making deQueue operation costly)
In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.
enQueue(q,  x)
  1) Push x to stack1 (assuming size of stacks is unlimited).

deQueue(q)
  1) If both stacks are empty then error.
  2) If stack2 is empty
       While stack1 is not empty, push everything from satck1 to stack2.
  3) Pop the element from stack2 and return it.
Method 2 is definitely better than method 1. Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation) moves the elements once and moves elements only if stack2 empty.

Code:Using Method 2
 #include<stdio.h>
#include<stdlib.h>

struct sNode
{
   int data;
   struct sNode *next;
};

struct queue
{
   struct sNode *stack1;
   struct sNode *stack2;
};

void push(struct sNode** top_ref, int new_data)
{
  struct sNode* new_node =
            (struct sNode*) malloc(sizeof(struct sNode));

  if(new_node == NULL)
  {
     printf("Stack overflow \n");
     getchar();
     exit(0);
  }        

  new_node->data  = new_data;

  new_node->next = (*top_ref);

  (*top_ref)    = new_node;
}

int pop(struct sNode** top_ref)
{
  int res;
  struct sNode *top;

  if(*top_ref == NULL)
  {
     printf("Stack overflow \n");
     getchar();
     exit(0);
  }
  else
  {
     top = *top_ref;
     res = top->data;
     *top_ref = top->next;
     free(top);
     return res;
  }
}

void enQueue(struct queue *q, int x)
{
   push(&q->stack1, x);
}

int deQueue(struct queue *q)
{
   int x;

   /* If both stacks are empty then error */
   if(q->stack1 == NULL && q->stack2 == NULL)
   {
      printf("Q is empty");
      getchar();
      exit(0);
   }

   /* Move elements from stack1 to stack 2 only if
       stack2 is empty */
   if(q->stack2 == NULL)
   {
     while(q->stack1 != NULL)
     {
        x = pop(&q->stack1);
        push(&q->stack2, x);
     }
   }

   x = pop(&q->stack2);
   return x;
}

int main()
{
   struct queue *q = (struct queue*)malloc(sizeof(struct queue));
   q->stack1 = NULL;
   q->stack2 = NULL;
   enQueue(q, 1);
   enQueue(q, 2);
   enQueue(q, 3);

   printf("%d  ", deQueue(q));
   printf("%d  ", deQueue(q));
   printf("%d  ", deQueue(q));

   getchar();
   return 0;
}

Queue using a single stack

Strategy:
Queue can be implemented using one user stack and one Function Call Stack.i.e using recursion


enQueue(x)
  1) Push x to stack1.

deQueue:
  1) If stack1 is empty then error.
  2) If stack1 has only one element then return it.
  3) Recursively pop everything from the stack1, store the popped item
    in a variable res,  push the res back to stack1 and return res
The step 3 makes sure that the last popped item is always returned and since the recursion stops when there is only one item in stack1 (step 2), we get the last element of stack1 in dequeue() and all other items are pushed back in step 3.

Code:
#include<stdio.h>
#include<stdlib.h>

struct sNode
{
   int data;
   struct sNode *next;
};

struct queue
{
  struct sNode *stack1;
};

void push(struct sNode** top_ref, int new_data)
{
  struct sNode* new_node =
            (struct sNode*) malloc(sizeof(struct sNode));

  if(new_node == NULL)
  {
     printf("Stack overflow \n");
     getchar();
     exit(0);
  }        

  new_node->data  = new_data;

  new_node->next = (*top_ref);

  (*top_ref)    = new_node;
}

int pop(struct sNode** top_ref)
{
  int res;
  struct sNode *top;

  if(*top_ref == NULL)
  {
     printf("Stack overflow \n");
     getchar();
     exit(0);
  }
  else
  {
     top = *top_ref;
     res = top->data;
     *top_ref = top->next;
     free(top);
     return res;
  }
}

void enQueue(struct queue *q, int x)
{
  push(&q->stack1, x);
}

int deQueue(struct queue *q)
{
   int x, res;

   /* If both stacks are empty then error */
   if(q->stack1 == NULL)
   {
     printf("Q is empty");
     getchar();
     exit(0);
   }
   else if(q->stack1->next == NULL)
   {
      return pop(&q->stack1);
   }
   else
   {

      x = pop(&q->stack1);

      res = deQueue(q);

      push(&q->stack1, x);

      return res;
   }
}

int main()
{
  struct queue *q = (struct queue*)malloc(sizeof(struct queue));
  q->stack1 = NULL;

  enQueue(q, 1);
  enQueue(q, 2);
  enQueue(q, 3); 

  printf("%d  ", deQueue(q));
  printf("%d  ", deQueue(q));
  printf("%d  ", deQueue(q));

  getchar();
}

Two stacks in a single array

Create a data structure twoStacks that represents two stacks. Implementation of twoStacks should use only one array, i.e., both stacks should use the same array for storing elements. Following functions must be supported by twoStacks.

push1(int x) –> pushes x to first stack
push2(int x) –> pushes x to second stack

pop1() –> pops an element from first stack and return the popped element
pop2() –> pops an element from second stack and return the popped element

Implementation of twoStack should be space efficient.

http://www.geeksforgeeks.org/implement-two-stacks-in-an-array/

Stack & Queue Problems

0.Simplify Path
http://www.programcreek.com/2014/04/leetcode-simplify-path-java/

1.Sliding Window Maximum

Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.
Examples:
Input :
arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}
k = 3
Output :
3 3 4 5 5 5 6
C++ Implementation:
http://www.geeksforgeeks.org/maximum-of-all-subarrays-of-size-k/
http://articles.leetcode.com/sliding-window-maximum/
Java Implementation:

2.Moving Average from Data Stream in a sliding window

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Moving Average from Data stream:
Given a stream of numbers, print average (or mean) of the stream at every point. For example, let us consider the stream as 10, 20, 30, 40, 50, 60, …
Average of 1 numbers is 10.00
  Average of 2 numbers is 15.00
  Average of 3 numbers is 20.00
  Average of 4 numbers is 25.00
  Average of 5 numbers is 30.00
  Average of 6 numbers is 35.00
  .................. 
 
Strategy:
To print mean of a stream, we need to find out how to find average when a new 
number is being added to the stream. To do this, all we need is count of numbers 
seen so far in the stream, previous average and new number. Let n be the count, 
prev_avg be the previous average and x be the new number being added. 
The average after including x number can be written as (prev_avg*n + x)/(n+1). 

Code:
#include <stdio.h>
 
// Returns the new average after including x
float getAvg(float prev_avg, int x, int n)
{
    return (prev_avg*n + x)/(n+1);
}
 
// Prints average of a stream of numbers
void streamAvg(float arr[], int n)
{
   float avg = 0;
   for(int i = 0; i < n; i++)
   {
       avg  = getAvg(avg, arr[i], i);
       printf("Average of %d numbers is %f \n", i+1, avg);
   }
   return;
}

int main()
{
    float arr[] = {10, 20, 30, 40, 50, 60};
    int n = sizeof(arr)/sizeof(arr[0]);
    streamAvg(arr, n);
    getchar();
    return 0;
}

The above function getAvg() can be optimized using following changes. We
can avoid the use of prev_avg and number of elements by using static 
variables (Assuming that only this function is called for average of 
stream). Following is the oprimnized version.
 
Revised Code:
 
#include <stdio.h>
 
// Returns the new average after including x
float getAvg (int x)
{
    static int sum, n;
 
    sum += x;
    return (((float)sum)/++n);
}
 
// Prints average of a stream of numbers
void streamAvg(float arr[], int n)
{
   float avg = 0;
   for(int i = 0; i < n; i++)
   {
       avg  = getAvg(arr[i]);
       printf("Average of %d numbers is %f \n", i+1, avg);
   }
   return;
}

int main()
{
    float arr[] = {10, 20, 30, 40, 50, 60};
    int n = sizeof(arr)/sizeof(arr[0]);
    streamAvg(arr, n);
    getchar();
    return 0;
}

3. Next higher element for each element in an array.
For e.g. if array is 1 2 3 4 5 8 6
o/p should be
(element) (next higher element)
1 2
2 3
3 4
4 5
5 8
8 nothing
6 nothing

Or
You are given an unsorted array A of n elements, now construct an array B for which B[i] = A[j] where j is the least number such that A[j] > A[i] and j>i if such a j does not exist B[i] = -1 Eg:
A={1,3,5,7,6,4,8}
B = {3 5 7 8 8 8 -1}
Approach:
While iterating over the array if the element is smaller than stack top, push it to stack along with index.if the element is larger than stack top, pop till current element is smaller than stack top and for all the popped indices store the current element.
Code:

#include<stdio.h>
#include<stdlib.h>
#define STACKSIZE 100

struct stack
{
    int top;
    int items[STACKSIZE];
};

void push(struct stack *ps, int x)
{
    if (ps->top == STACKSIZE-1)
    {
        printf("Error: stack overflow\n");
        getchar();
        exit(0);
    }
    else
    {
        ps->top += 1;
       ps->items[ps->top] = x;
    }
}

bool isEmpty(struct stack *ps)
{
    return (ps->top == -1)? true : false;
}

int pop(struct stack *ps)
{
    int temp;
    if (ps->top == -1)
    {
        printf("Error: stack underflow \n");
        getchar();
        exit(0);
    }
    else
    {
        temp = ps->items[ps->top];
        ps->top -= 1;
        return temp;
    }
}

void printNGE(int arr[], int n)
{
    int i = 0;
    struct stack s;
    s.top = -1;
    int element, next;

    push(&s, arr[0]);


    for (i=1; i<n; i++)
    {
        next = arr[i];

        if (isEmpty(&s) == false)
        {
            element = pop(&s);

            while (element < next)
            {
                printf("\n %d --> %d", element, next);
                if(isEmpty(&s) == true)
                   break;
                element = pop(&s);
            }
            if (element > next)
                push(&s, element);
        }
        push(&s, next);
    }

    while(isEmpty(&s) == false)
    {
        element = pop(&s);
        next = -1;
        printf("\n %d --> %d", element, next);
    }
}

int main()
{
    int arr[]= {11, 13, 21, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    printNGE(arr, n);
    getchar();
    return 0;
}
Time Complexity:O(n)
Simple Code in Java [ Easy to understand ]
public class Test {

    public static void upateArray(int[] a){
        Stack<Integer> stack = new Stack<Integer>();
        int len = a.length;
        int cur = 0;
        while(cur < len){
            while(!stack.isEmpty() && a[stack.peek()] < a[cur]){
                a[stack.pop()] = a[cur];
            }
            stack.push(cur);
            cur++;
        }
    }

    public static void main (String args[]){
        int a[] = {3,2,5,11,4,11,13,8,6,20,10};
        upateArray(a);
        for(int i : a)
            System.out.print(" "+i);
    }
}
 
Source:
http://stackoverflow.com/questions/5007941/next-larger-number-in-an-array 
 
Method 2:
Make an empty array called c[].
Start at the end of a[] and work backwards.
Do a binary search in c[] for the first value greater than a[i]. Put that into b[i], or a -1 if you can't find one.
Drop everything in c[] that is less than b[i].
Append a[i] to the beginning of c[].
c[] will always be sorted, allowing binary search.

For example, with the sample A={1,3,5,7,6,4,8}
Start at the end, A[i]=8, C={}
First iteration is a bit weird.
Binary search of C for the first value greater than 8 gives nothing, so B[i] = -1
You don't have to drop anything from C because it is empty, but you would have had to empty it anyway because of the -1.
Append A[i]=8 to the beginning of C, so C={8}
Now A[i]=4, C={8}
Binary search of C for the first value greater than 4 gives 8, so B[i]=8
Drop everything less than 8 from C, which still leaves C={8}
Append A[i]=4 to the beginning of C, so C={4,8}
Now A[i]=6, C={4,8}
Binary search of C for the first value greater than 6 gives 8, so B[i]=8
Drop everything less than 8 from C, which leaves C={8}
Append A[i]=6 to the beginning of C, so C={6,8}
Now A[i]=7, C={6,8}
Binary search of C for the first value greater than 7 gives 8, so B[i]=8
Drop everything less than 8 from C, which leaves C={8}
Append A[i]=7 to the beginning of C, so C={7,8}
Now A[i]=5, C={7,8}
Binary search of C for the first value greater than 5 gives 7, so B[i]=7
Drop everything less than 7 from C, which leaves C={7,8}
Append A[i]=5 to the beginning of C, so C={5,7,8}
Now A[i]=3, C={5,7,8}
Binary search of C for the first value greater than 3 gives 5, so B[i]=5
Drop everything less than 5 from C, which leaves C={5,7,8}
Append A[i]=3 to the beginning of C, so C={3,5,7,8}
Now A[i]=1, C={3,5,7,8}
Binary search of C for the first value greater than 1 gives 3, so B[i]=3
Done



Wednesday, December 14, 2011

Balanced Parenthesis in an expression

Question 1:
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[","]” are correct in exp. For example, the program should print true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”

Question 2:
Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.

Question 3:
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
http://www.programcreek.com/2012/12/leetcode-valid-parentheses-java/

Question 4:
You have been asked to Write an algo­rithm to find Whether Given the Sequence of paren­the­ses are well formed
http://algorithms.tutorialhorizon.com/algorithms-find-whether-given-the-sequence-of-parentheses-are-well-formed/

Question 5:
Print All Possible Valid Combinations Of Parenthesis of Given ‘N’
http://algorithms.tutorialhorizon.com/generate-all-valid-parenthesis-strings-of-length-2n-of-given-n/

Strategy:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[') then push it to stack.
b) If the current character is a closing bracket (')' or '}' or ']‘) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”

Code:
 #include <stdio.h>
#include <stdlib.h>

#define bool int

struct sNode
{
char data;
struct sNode *next;
};
void push(struct sNode** top_ref, int new_data)
{

struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));

if(new_node == NULL)
   {
    printf("Stack overflow \n");
    getchar();
    exit(0);
   }

new_node->data = new_data;

new_node->next = (*top_ref);

(*top_ref) = new_node;
}

int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;

/*If stack is empty then error */
if(*top_ref == NULL)
  {
    printf("Stack overflow \n");
    getchar();
    exit(0);
  }
else
  {
    top = *top_ref;
    res = top->data;
    *top_ref = top->next;
    free(top);
    return res;
  }
}

//ALGORITHM  START

bool isMatchingPair(char character1, char character2)
{
if(character1 == '(' && character2 == ')')
return 1;
else if(character1 == '{' && character2 == '}')
return 1;
else if(character1 == '[' && character2 == ']')
return 1;
else
return 0;
}

bool areParenthesisBalanced(char exp[])
{
int i = 0;

struct sNode *stack = NULL;

while(exp[i])
{
if(exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);

if(exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{

if(stack == NULL)
return 0;

else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}

/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if(stack == NULL)
return 1;
else
return 0;
}

int main()
{
char exp[100] = "[{()}]";
if(areParenthesisBalanced(exp))
printf("\n Balanced ");
else
printf("\n Not Balanced "); \
getchar();
}

Queue Implementation

Queue:
Implement a queue[ Add( ) and Delete( )] operations using

1.Circular Array
2.Singly Linked Lists and TWO POINTERS
3.Circular Linked List and SINGLE POINTER

Deque:
Implement the following Deque operations  using i)Linked List ii)Stacks

1.Enqueue (  )
2.Dequeue ( )

Priority Queue using LINKED LIST .Discuss advantage of Priority Queue.

http://quiz.geeksforgeeks.org/priority-queue-set-1-introduction/
http://www.geeksforgeeks.org/why-is-binary-heap-preferred-over-bst-for-priority-queue/

void INSERT_QUEUE_TWO(struct node *&front, struct node *&rear,int data)
{struct node *tmp;
 tmp=(struct node *)malloc(sizeof(struct node));
 tmp->info=data;
 tmp->link=NULL;

 if(front==NULL)
    front=tmp;
 else
    rear->link=tmp;//LAST NODE POINTS TO TMP
 rear=tmp;//REAR ALSO POINTS TO TMP
}

void INSERT_QUEUE_SINGLE(struct node *&rear,int data)
//INSERTION is at the beginning of a CIRCULAR LL
{struct node *q,*tmp;
 tmp=(struct node *)malloc(sizeof(struct node));
 tmp->info=data;

if(rear==NULL)
    {rear=tmp;
    tmp->link=rear;}
else
    {tmp->link=rear->link;
     rear->link=tmp;
     rear=tmp;}
}

void DELETE_QUEUE_TWO(struct node *&front,struct node *&rear,int data)
{struct node *tmp;
 if (front==NULL)
    printf("Queue UNDEFLOW");
 else
    {tmp=front;//Delete From Front
    front=front->link;
    free(tmp);}
}

void DELETE_QUEUE_SINGLE(struct node *&rear)
{struct node *tmp,*q;
 if (rear==NULL)
    {printf("Queue UNDEFLOW");
    return;}
   
 if(rear->link==rear)//ONLY ONE ELEMENT
    {tmp=rear;
     rear=NULL;
     free(tmp);
     return;}
   
tmp=rear->link;
rear->link=tmp->link;
free(tmp);
}