Smaller on Left

 Given an array arr[] of integers, for each element in the array, find the nearest smaller element on its left. If there is no such smaller element, return -1 for that position.


Input: arr[] = [1, 6, 2]

Output: [-1, 1, 1]

Explaination: 

There is no number to the left of 1, so we return -1. 

After that, the number is 6, and the nearest smaller number on its left is 1. 

Next, the number is 2, and the nearest smaller number on the left is also 1.

Input: arr[] = [1, 5, 0, 3, 4, 5]

Output: [-1, 1, -1, 0, 3, 4]

Explaination: 

There is no number to the left of 1,  so we return -1. 

After that, the number is 5,  and the nearest smaller number on its left is 1. 

 Next, the number is 0, and there is no smaller number on the left, so we return -1.

Then comes 3, and the nearest smaller number on its left is 0.

After that, the number is 4, and the nearest smaller number on the left is 3. 

Finally, the number is 5, and the nearest smaller number on its left is 4.

Right To Left Traverse 


class Solution {
    public int[] leftSmaller(int[] arr) {
        // code here
         int n = arr.length;
        int[] result = new int[n];
        Arrays.fill(result, -1);
        Stack<Integer> st = new Stack<>(); // stores indices

        for (int i = n - 1; i >= 0; i--) {
            // For all elements to the right that are greater, assign arr[i] as their left smaller
            while (!st.isEmpty() && arr[i] < arr[st.peek()]) {
                int index = st.pop();
                result[index] = arr[i];
            }
            st.push(i); // store index
        }

        return result;
    }
}



Left To Right Traverse

class Solution {
    public int[] leftSmaller(int[] arr) {
        // code here
       
           int n = arr.length;
        int[] result = new int[n];
        Arrays.fill(result, -1);

        Stack<Integer> st = new Stack<>(); // stack stores indices

        for (int i = 0; i < n; i++) {
            while (!st.isEmpty() && arr[st.peek()] >= arr[i]) {
                st.pop();
            }

            if (!st.isEmpty()) {
                result[i] = arr[st.peek()];
            }

            st.push(i); // push current index
        }

        return result;
       
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence