Problem Solving using Stack Data Structure

Please try to solve these problems yourself before seeing the Algorithm or Solution.

  • Algorithm
    • Take input n
    • Then declare an arr[n] and take all the n inputs using for loop.
    • Declare a structure to keep the number and index from an array.
    • Using the above structure declares Stack.
    • Declare two arrays of size n, x[n] and y[n].
    • In x[n] we will keep the index of the immediate largest number left to the ith number.
    • Similarly y[n] to keep the index of the immediate largest number right side.
    • In that stack check whether the top value is greater or not. If it is greater then arr[i] assign that index to x[i] and push the (arr[i],i) to the stack.
    • If less then pop the value from the stack and check with the next top. If the stack gets empty and you didn't find it then x[i]=-1;
    • Similarly for filling y[i] do the same thing as above two steps but from the opposite side of the array.
    • Then add both res[i]=x[i]+y[i] and at end print.
    • You have got your answer.

  • Algorithm
    • Take the input string s.
    • Make a stack to keep the integer value of the character.
    • As integer is easy to handle.
    • Now using for a loop traverses the string and check whether the top value of the stack is the same as (int)s[i], if yes then pop else push it in.
    • Now pop the value from this stack and push it to another stack as this will reverse the reversed string.
    • After this pop, the value, convert it to character and print without space.
    • This will give you the answer.