Varun

Idea is to do DFS and flag each boxes

/*2 0 3 0 02 0 0 4 42 2 0 0 0*/class Solution{public int countClusters(int mat[][]){int count = 0;int dec = 2;int m = mat.length;int n = mat[0].length;for(int i=0;i<m;i++){for(int j=0;j<n;j++){if(mat[i][j]==1){helper(mat, i,j, dec);dec++;count++;}}}return count;}public void helper(int[][] mat, int i, int j,int dec){if(i<0 || i>mat.length || j<0 || j>mat[0].length || mat[i][j]!=1){return;}mat[i][j] = dec;helper(mat, i+1,j,dec);helper(mat, i-1, j,dec);helper(mat ,i,j+1, dec);helper(mat, i, j-1,dec);}}

--

--

Question: Given an array of integers, returns a list for all elements for which elements to the right are smaller ( Or current element is greater than the elements to the right )

Photo by Markus Spiske on Unsplash

We need to use a stack for this as through a stack we can keep track of the elements to the right and conditionally pop the elements when we get the top of the stack smaller than the current element.

class Solution{    static ArrayList<Integer> leaders(int arr[], int n){

ArrayList<Integer> res = new ArrayList<>();
if(n==0) return res;
Stack<Integer> stack = new Stack<>();
stack.push(arr[n-1]);
for(int i=n-1;i>=0;i--)
{
while(!stack.isEmpty() && stack.peek()<=arr[i])
{
stack.pop();
}

if(stack.size()==0)
res.add(arr[i]);
stack.push(arr[i]);
}
Collections.reverse(res);
return res;
}
}

--

--

Varun

Varun

MEAN stack developer | AI enthusiast