Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions Projects/Algorithms/Stack/nextGreaterElement.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import java.util.*;

public class NextGreaterElement {

/**
* Function to find Next Greater Element for each element in the array.
*
* @param arr Input array of integers
* @return Array containing next greater elements
*/
public static int[] findNextGreater(int[] arr) {
int n = arr.length;
int[] result = new int[n];

// Stack to store elements
Stack<Integer> stack = new Stack<>();

// Traverse from right to left
for (int i = n - 1; i >= 0; i--) {

// Remove elements from stack that are <= current element
while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
}

// If stack is empty, no greater element exists
if (stack.isEmpty()) {
result[i] = -1;
} else {
// Top of stack is the next greater element
result[i] = stack.peek();
}

// Push current element onto stack
stack.push(arr[i]);
}

return result;
}

/**
* Driver method to test the function
*/
public static void main(String[] args) {
int[] arr = {4, 5, 2, 10, 8};

int[] result = findNextGreater(arr);

System.out.println("Next Greater Elements:");
for (int num : result) {
System.out.print(num + " ");
}
}
}
1 change: 1 addition & 0 deletions Projects/JournalApp
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this file used for?

Could you please provide clarification on this?

Thanks

Submodule JournalApp added at 113662
21 changes: 21 additions & 0 deletions Projects/Patterns/pyramidPattern.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class PyramidPattern {
public static void main(String[] args) {
int n = 5; // number of rows

for (int i = 1; i <= n; i++) {

// print spaces
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}

// print stars
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}

// move to next line
System.out.println();
}
}
}