You've learned to search, count, and find pairs. Now let's unlock a technique that's deceptively simple but incredibly powerful — tracking a running minimum and maximum in a single pass. 🏃♂️
Imagine you're walking through a flea market with dozens of stalls, each selling the same vintage t-shirt at different prices. You want to know the cheapest and most expensive prices — but you can only walk through once (the market is closing!). What do you do? 🛒
In code, this looks like:
⏱ Time Complexity: O(n) — One pass through the array, two comparisons per element. Can't do better than this!
💾 Space Complexity: O(1) — Just two variables: min_val and max_val. No extra arrays or dictionaries. Your brain (well, two variables) is all you need. 🧠
🔮 Why this matters: The next problem is Best Time to Buy and Sell Stock — one of the most famous interview questions ever. Its core trick? Tracking a running minimum as you scan through prices. If you nail min/max tracking here, that problem becomes a cakewalk. Let's practice!
def find_min_max(arr):
min_val = arr[0]
max_val = arr[0]
for num in arr[1:]:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
return min_val, max_val
lo, hi = find_min_max([3, 7, 1, 9, 4, 2])
print(f"Min: {lo}, Max: {hi}")
lo, hi = find_min_max([100, -5, 42, 0, 88])
print(f"Min: {lo}, Max: {hi}")
lo, hi = find_min_max([42])
print(f"Min: {lo}, Max: {hi}")