Arrays & Hashing Starter
The foundation of technical interviews and competitive problem solving. Learn how frequency counters and lookup hash maps turn brute-force O(N²) solutions into optimal O(N) algorithms.
Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Examples
- 2 <= nums.length <= 10^4
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
- Only one valid answer exists.
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
# Use a hash map to store complement -> index
seen = {}
for i, n in enumerate(nums):
diff = target - n
if diff in seen:
return [seen[diff], i]
seen[n] = i
return []Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Examples
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
class Solution:
def containsDuplicate(self, nums: list[int]) -> bool:
seen = set()
for n in nums:
if n in seen:
return True
seen.add(n)
return FalseValid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Examples
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t): return False
counts = [0] * 26
for c1, c2 in zip(s, t):
counts[ord(c1) - ord('a')] += 1
counts[ord(c2) - ord('a')] -= 1
return all(c == 0 for c in counts)Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Examples
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
class Solution:
def maxProfit(self, prices: list[int]) -> int:
min_price = float('inf')
max_profit = 0
for p in prices:
if p < min_price:
min_price = p
elif p - min_price > max_profit:
max_profit = p - min_price
return max_profitMaximum Subarray (Kadane)
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Examples
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
cur_sum = 0
max_sum = nums[0]
for n in nums:
cur_sum = max(n, cur_sum + n)
max_sum = max(max_sum, cur_sum)
return max_sum