Finding a value in a sorted array is a familiar binary-search problem. Finding its first occurrence adds a small but important requirement: when the middle value matches, you cannot stop. An earlier copy may still be waiting on the left. In this exercise, we will build one iterative solution in Python and Java, trace every boundary change, explain why it is correct, and test the cases that commonly cause off-by-one errors. The same idea also finds the insertion position for a missing value. The problem and input contract Given an integer array sorted in nondecreasing order and an integer target, return the zero-based index of the target's first occurrence. Return -1 when it is absent. Repeated values are allowed. The input must already be sorted, and the algorithm does not modify it. For [1, 2, 2, 2, 5] and target 2 , the answer is 1 , not 2 or 3. For the same array and target 4 , the answer is -1 . An empty array also returns -1 . Both implementations expect an array or lis...
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]: ...