Problem A string contains only (), [] and {}. Return whether every opening bracket closes in reverse order. Worked example {[()]} is valid. ([)] fails when ) meets [. Read {, [, and ( in that order. The most recent opener must close first, so ) removes (, ] removes [, and } removes {. For ([)], the first closer is ) while [ is still on top. Stop immediately. How the solution works The stack holds unmatched openers, with the most recent one on top. An empty stack at the end means no opening bracket remains. Python stores opening brackets. Java stores the closing bracket it expects, so the two versions enforce the same order. Counting opening and closing brackets alone misses crossed pairs like ([)]. Python solution def valid_brackets(text): closing = {')': '(', ']': '[', '}': '{'} stack = [] for char in text: if char not in closing: stack.append(char) elif not stack or stack.pop() != closing[char]: ...
Problem Given a list of integers and a target, return two distinct indices whose values add to the target. Return None in Python or null in Java if no pair exists. Worked example For [4, 1, 6, 2] with target 8, return (2, 3). Insert 4 at index 0 and 1 at index 1. At index 2, 6 needs 2, which has not appeared yet. At index 3, 2 needs 6, and the map returns index 2. How the solution works The map contains only earlier indices, so the first match gives two distinct indices. Every pair can be found when the algorithm visits its later index. Checking the map before insertion prevents a single 4 from being used twice when the target is 8. The Java version uses long for the complement so integer overflow cannot produce a false match. Python solution def two_sum(nums, target): seen = {} for index, value in enumerate(nums): complement = target - value if complement in seen: return seen[complement], index seen[value] = index return None Java soluti...