Thursday, June 23, 2011

WAP to Create New Arrayfrom Given Array Suuch That array2[i] will hold the value of the left-most integer from the range array1[i+1] to array1[n-1] such that it is greater than array1[i]. If no such element exists, assign -1.

You are given an array of integers, say array1 of size n. You have to create another array (say array2) and fill its contents by following this rule: array2[i] will hold the value of the left-most integer from the range array1[i+1] to array1[n-1] such that it is greater than array1[i]. If no such element exists, assign -1.

Example ar[]={4,5,2,25}
4 --> 5
5 --> 25
2 --> 25
25 --> -1
arr[]=1 21 8 11 13 9 6
1- 21
21- -1
8 11
11 13
13 -1
9 -1
6 -1

Data Structure:

Algorithm:


Time Complexity O(N^2)
Space Complexity O(1)
Run here

Optimize Approach



Time Complexity O(N)
Space Complexity O(N) Stack Space
Run here

No comments :