Order them

Given an array of integers A describing ranking of trucks. Your task is to insert these rank in another array B
by some means of operations such that B is sorted in ascending order.
For performing these operations you can use one stack C.

In one Operation you can perform any of the following steps:

  1. Remove the first element from A and append at the back of C.
  2. Remove the last element from C and append at the back of B.
  3. Remove the first element from A and append at the back of B.

you can perform these operations any number of times (possibly zero).

Return 1 if B can be formed in ascending order using some operations else return 0.



Input Format

The only argument given is the integer array A.

Output Format

   Return 1 if B can be formed in ascending order using some operations else return 0.

Constraints

1 <= length of the array <= 100000
1 <= A[i] <= length of Array
All elements of A are distinct.

For Example

Input 1:
    A = [5, 1, 2, 4, 3]
Output 1:
    1
    step 1: A = [5, 1, 2, 4, 3]
            B = []
            C = []
    step 2: A = [1, 2, 4, 3]
            B = [5]
            C = []
    step 3: A = [2, 4, 3]
            B = [5]
            C = [1]
    step 4: A = [4, 3]
            B = [5]
            C = [1, 2]
    step 5: A = [3]
            B = [5, 4]
            C = [1, 2]
    step 6: A = []
            B = [5, 4]
            C = [1, 2, 3]
    step 7: A = []
            B = [5]
            C = [1, 2, 3, 4]
    step 8: A = []
            B = []
            C = [1, 2, 3, 4, 5]
    
    

Input 2:
    A = [5, 3, 1, 4, 2]
Output 2:
    0
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Order them on Interview Code Editor
Sign Up
to access hints and editorial solutions for Order them

Discussion


Loading...
Click here to start solving coding interview questions