Skip to content
Open
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
55 changes: 33 additions & 22 deletions src/main/java/com/thealgorithms/stacks/BalancedBrackets.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ private BalancedBrackets() {
/**
* Check if {@code leftBracket} and {@code rightBracket} is paired or not
*
* @param leftBracket left bracket
* @param leftBracket left bracket
* @param rightBracket right bracket
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is
* paired, otherwise {@code false}
* paired, otherwise {@code false}
*/
public static boolean isPaired(char leftBracket, char rightBracket) {
char[][] pairedBrackets = {
{'(', ')'},
{'[', ']'},
{'{', '}'},
{'<', '>'},
{ '(', ')' },
{ '[', ']' },
{ '{', '}' },
{ '<', '>' },
};
for (char[] pairedBracket : pairedBrackets) {
if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
Expand All @@ -48,7 +48,7 @@ public static boolean isPaired(char leftBracket, char rightBracket) {
*
* @param brackets the brackets
* @return {@code true} if {@code brackets} is balanced, otherwise
* {@code false}
* {@code false}
*/
public static boolean isBalanced(String brackets) {
if (brackets == null) {
Expand All @@ -57,24 +57,35 @@ public static boolean isBalanced(String brackets) {
Stack<Character> bracketsStack = new Stack<>();
for (char bracket : brackets.toCharArray()) {
switch (bracket) {
case '(':
case '[':
case '<':
case '{':
bracketsStack.push(bracket);
break;
case ')':
case ']':
case '>':
case '}':
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
case '(':
case '[':
case '<':
case '{':
bracketsStack.push(bracket);
break;
case ')':
case ']':
case '>':
case '}':
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
return false;
}
break;
default:
return false;
}
break;
default:
return false;
}
}
return bracketsStack.isEmpty();
}
}

/**
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* reasons:
* 1. The time complexity of the isBalanced method is O(n), where n is the
* length of the input string.
* 2. The space complexity of the isBalanced method is O(n), where n is the
* length of the input string.
*/
18 changes: 16 additions & 2 deletions src/main/java/com/thealgorithms/stacks/CelebrityFinder.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
/**
* Solves the celebrity problem using a stack-based algorithm.
*
* <p>Celebrity is someone known by everyone but doesn't know anyone else.
* <p>Applications: Graph theory and social network analysis.
* <p>
* Celebrity is someone known by everyone but doesn't know anyone else.
* <p>
* Applications: Graph theory and social network analysis.
*
* @author Hardvan
*/
Expand Down Expand Up @@ -50,3 +52,15 @@ public static int findCelebrity(int[][] party) {
return candidate;
}
}

/**
* Time Complexity: O(n)
* reason:- Because each person is processed a constant number of times:
* once when pushed, once during candidate elimination, and once during
* verification.
* -----------------------------------------------------------------------------
*
* Space Complexity: O(n)
* reason:- Due to the stack storing up to n people in the worst case.
*
*/
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,38 @@
* Utility class for converting a non-negative decimal (base-10) integer
* to its representation in another radix (base) between 2 and 16, inclusive.
*
* <p>This class uses a stack-based approach to reverse the digits obtained from
* <p>
* This class uses a stack-based approach to reverse the digits obtained from
* successive divisions by the target radix.
*
* <p>This class cannot be instantiated.</p>
* <p>
* This class cannot be instantiated.
* </p>
*/
public final class DecimalToAnyUsingStack {

private DecimalToAnyUsingStack() {
}

private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };

/**
* Convert a decimal number to another radix.
*
* @param number the number to be converted
* @param radix the radix
* @param radix the radix
* @return the number represented in the new radix as a String
* @throws IllegalArgumentException if number is negative or radix is not between 2 and 16 inclusive
* @throws IllegalArgumentException if number is negative or radix is not
* between 2 and 16 inclusive
*/
public static String convert(int number, int radix) {
if (number < 0) {
throw new IllegalArgumentException("Number must be non-negative.");
}
if (radix < 2 || radix > 16) {
throw new IllegalArgumentException(String.format("Invalid radix: %d. Radix must be between 2 and 16.", radix));
throw new IllegalArgumentException(
String.format("Invalid radix: %d. Radix must be between 2 and 16.", radix));
}

if (number == 0) {
Expand All @@ -52,3 +58,10 @@ public static String convert(int number, int radix) {
return result.toString();
}
}

/**
* Time Complexity: O(log n) - The number of divisions by the radix determines
* the iterations.
* Space Complexity: O(log n) - Stack depth depends on the number of digits in
* the new base.
*/
15 changes: 13 additions & 2 deletions src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import java.util.Stack;

/**
* Class for detecting unnecessary or redundant brackets in a mathematical expression.
* Assumes the expression is balanced (i.e., all opening brackets have matching closing brackets).
* Class for detecting unnecessary or redundant brackets in a mathematical
* expression.
* Assumes the expression is balanced (i.e., all opening brackets have matching
* closing brackets).
*/
public final class DuplicateBrackets {
private DuplicateBrackets() {
Expand Down Expand Up @@ -42,3 +44,12 @@ public static boolean check(String expression) {
return false;
}
}

/**
* Time Complexity: O(n)
* reason - Iterates through the expression once; each character is processed
* constant times.
* Space Complexity: O(n)
* reason - Stack stores characters, growing linearly with expression length in
* worst case.
*/
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public GreatestElementConstantTime() {
* Pushes an element onto the top of the stack.
* Checks if the element is the maximum or not
* If so, then pushes to the maximum stack
*
* @param data The element to be pushed onto the stack.
*/
public void push(int data) {
Expand Down Expand Up @@ -63,7 +64,8 @@ public void pop() {
/**
* Returns the maximum element present in the stack
*
* @return The element at the top of the maxStack, or null if the stack is empty.
* @return The element at the top of the maxStack, or null if the stack is
* empty.
*/
public Integer getMaximumElement() {
if (maxStack.isEmpty()) {
Expand All @@ -72,3 +74,15 @@ public Integer getMaximumElement() {
return maxStack.peek();
}
}

/**
* ime Complexity: O(1)
* Reason: Detailed operations like push, pop, and getMaximumElement
* only involve basic stack operations (push/pop/peek) and constant-time
* comparisons, so they all run in constant time.
* -----------------------------------------------------------------
* Space Complexity: O(n)
* Reason: An auxiliary stack (maxStack) is used. In the worst case (e.g.,
* elements pushed in ascending order), it stores all n elements.
*
*/
36 changes: 23 additions & 13 deletions src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
/**
* Utility class for evaluating postfix expressions using integer arithmetic.
* <p>
* Postfix notation, also known as Reverse Polish Notation (RPN), is a mathematical notation in which operators follow their operands.
* This class provides a method to evaluate expressions written in postfix notation.
* Postfix notation, also known as Reverse Polish Notation (RPN), is a
* mathematical notation in which operators follow their operands.
* This class provides a method to evaluate expressions written in postfix
* notation.
* </p>
* <p>
* For more information on postfix notation, refer to
* <a href="https://en.wikipedia.org/wiki/Reverse_Polish_notation">Reverse Polish Notation (RPN) on Wikipedia</a>.
* <a href="https://en.wikipedia.org/wiki/Reverse_Polish_notation">Reverse
* Polish Notation (RPN) on Wikipedia</a>.
* </p>
*/
public final class StackPostfixNotation {
Expand All @@ -22,16 +25,16 @@ private StackPostfixNotation() {
private static BiFunction<Integer, Integer, Integer> getOperator(final String operationSymbol) {
// note the order of operands
switch (operationSymbol) {
case "+":
return (a, b) -> b + a;
case "-":
return (a, b) -> b - a;
case "*":
return (a, b) -> b * a;
case "/":
return (a, b) -> b / a;
default:
throw new IllegalArgumentException("exp contains an unknown operation.");
case "+":
return (a, b) -> b + a;
case "-":
return (a, b) -> b - a;
case "*":
return (a, b) -> b * a;
case "/":
return (a, b) -> b / a;
default:
throw new IllegalArgumentException("exp contains an unknown operation.");
}
}

Expand Down Expand Up @@ -70,3 +73,10 @@ public static int postfixEvaluate(final String exp) {
return s.pop();
}
}
/**
* Time Complexity: O(n)
* Reason - The expression is tokenized and scanned once. Each operation takes
* constant time.
* Space Complexity: O(n)
* Reason - The stack can store up to O(n) operands in the worst case.
*/
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,11 @@ public int size() {
return mainQueue.size();
}
}
/*
* push: O(n) — requires moving all existing elements to maintain LIFO order.
* pop: O(1) — direct removal from the main queue.
* peek: O(1).
* isEmpty / size: O(1).
* -----------------------------------------------------------------
* Space Complexity: O(n) — total elements stored across two queues.
*/
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package com.thealgorithms.stacks;

/**
* Trapping Rainwater Problem
* Given an array of non-negative integers representing the height of bars,
Expand Down Expand Up @@ -46,3 +47,10 @@ public static int trap(int[] height) {
return result;
}
}

/**
* Time Complexity - O(n)
* reason:- The algorithm scans the array once.
* Space Complexity - O(1)
* reason:- Constant space is used.
*/
13 changes: 12 additions & 1 deletion src/main/java/com/thealgorithms/stacks/ValidParentheses.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
/**
* Valid Parentheses Problem
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
* Given a string containing just the characters '(', ')', '{', '}', '[' and
* ']',
* determine if the input string is valid.
*
* An input string is valid if:
Expand Down Expand Up @@ -72,3 +73,13 @@ public static boolean isValid(String s) {
return stack.isEmpty();
}
}

/**
* Time Complexity: O(n)
* The algorithm scans the string once, and all operations inside
* the loop (map lookup, stack push/pop) run in constant time.
*
* Space Complexity: O(n)
* In the worst case, the stack holds half of the characters, growing linearly
* with input size.
*/
Loading