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
39 changes: 39 additions & 0 deletions Java/KadanesAlgorithm.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
public class KadanesAlgorithm {

/**
* Kadane's Algorithm to find the maximum sum of a contiguous subarray.
* Problem (saloni-jaiswal-dev#358)
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* Test Cases:
* Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4] Expected: 6
* Input: [1] Expected: 1
* Input: [5, 4, -1, 7, 8] Expected: 23
* Input: [-1, -2, -3, -4] Expected: -1
*/
public static int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException("Input array must not be null or empty.");
}
int maxSoFar = nums[0];
int currentMax = nums[0];
for (int i = 1; i < nums.length; i++) {
currentMax = Math.max(nums[i], currentMax + nums[i]);
maxSoFar = Math.max(maxSoFar, currentMax);
}
return maxSoFar;
}

public static void main(String[] args) {
int[] nums1 = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Test 1: " + maxSubArray(nums1)); // 6
int[] nums2 = {1};
System.out.println("Test 2: " + maxSubArray(nums2)); // 1
int[] nums3 = {5, 4, -1, 7, 8};
System.out.println("Test 3: " + maxSubArray(nums3)); // 23
int[] nums4 = {-1, -2, -3, -4};
System.out.println("Test 4: " + maxSubArray(nums4)); // -1
}
}
55 changes: 55 additions & 0 deletions Java/LongestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Longest Common Prefix
*
* Problem: Write a function to find the longest common prefix string
* amongst an array of strings. If there is no common prefix, return "".
*
* Approach: Horizontal scanning - compare prefix with each string
* Time Complexity: O(S) where S = sum of all characters in all strings
* Space Complexity: O(1)
*/
public class LongestCommonPrefix {

public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}

// Start with the first string as the initial prefix
String prefix = strs[0];

for (int i = 1; i < strs.length; i++) {
// Reduce the prefix until it matches the start of strs[i]
while (!strs[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}

return prefix;
}

public static void main(String[] args) {
// Test Case 1: Common prefix "fl"
String[] strs1 = {"flower", "flow", "flight"};
System.out.println("Test 1: " + longestCommonPrefix(strs1)); // Expected: "fl"

// Test Case 2: No common prefix
String[] strs2 = {"dog", "racecar", "car"};
System.out.println("Test 2: " + longestCommonPrefix(strs2)); // Expected: ""

// Test Case 3: All strings are the same
String[] strs3 = {"abc", "abc", "abc"};
System.out.println("Test 3: " + longestCommonPrefix(strs3)); // Expected: "abc"

// Test Case 4: Single string
String[] strs4 = {"alone"};
System.out.println("Test 4: " + longestCommonPrefix(strs4)); // Expected: "alone"

// Test Case 5: Empty string in array
String[] strs5 = {"", "b"};
System.out.println("Test 5: " + longestCommonPrefix(strs5)); // Expected: ""
}
}
60 changes: 60 additions & 0 deletions Python/valid_parentheses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
Valid Parentheses Problem
Issue: #317 (saloni-jaiswal-dev/DSA_Problems)

Problem:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.

A string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.

Approach (Stack-based):
- Use a stack to track unmatched opening brackets.
- For each character in the string:
* If it's an opening bracket, push it onto the stack.
* If it's a closing bracket, check if it matches the top of the stack.
- If it matches, pop the stack.
- If it doesn't match (or stack is empty), return False.
- At the end, the string is valid only if the stack is empty.

Time Complexity : O(n) — single pass through the string
Space Complexity: O(n) — stack can hold at most n/2 brackets
"""


def is_valid(s: str) -> bool:
stack = []
matching = {')': '(', '}': '{', ']': '['}

for char in s:
if char in '({[':
stack.append(char)
elif char in ')}]':
if not stack or stack[-1] != matching[char]:
return False
stack.pop()

return len(stack) == 0


if __name__ == "__main__":
test_cases = [
("()", True),
("()[]{}", True),
("(]", False),
("([)]", False),
("{[]}", True),
("", True),
("{", False),
]

print("Valid Parentheses — Test Results")
print("-" * 40)
for s, expected in test_cases:
result = is_valid(s)
status = "PASS" if result == expected else "FAIL"
print(f"[{status}] is_valid({s!r}) = {result} (expected {expected})")