💬 class Solution: def searchRange(self, nums: list[int], target: int) -> list[int]: first = -1 left = 0 right = len(nums) - 1
# Record each match and keep searching left for an earlier one. while left <= right: mid = left + (right - left) // 2 if nums[mid] < target: left = mid + 1 elif nums[mid] > target: right = mid - 1 else: first = mid right = mid - 1
💬 class Solution: def search(self, nums: list[int], target: int) -> int: """Find target in O(log n) time using O(1) extra space.""" left = 0 right = len(nums) - 1
# Any possible match is inside the inclusive range [left, right]. while left <= right: mid = (left + right) // 2 value = nums[mid]
if value == target: return mid if value < target: left = mid + 1 else: right = mid - 1
💬 class Solution: def subarraysDivByK(self, nums: list[int], k: int) -> int: """Count nonempty contiguous subarrays whose sum is divisible by k.
nums may contain negative numbers and zeros; k is positive. Time: O(n + k). Extra space: O(k). """ # Equal prefix remainders mean their difference is divisible by k. seen = [0] * k seen[0] = 1 # The empty prefix has remainder zero. remainder = 0 count = 0
for num in nums: # Python's modulo with positive k also handles negative sums. remainder = (remainder + num) % k count += seen[remainder] # Record this prefix after counting to exclude empty subarrays. seen[remainder] += 1
💬 class Solution: def findMaxLength(self, nums: list[int]) -> int: first_seen = {0: -1} balance = 0 best = 0 get = first_seen.get for i, num in enumerate(nums): balance += 1 if num else -1 earlier = get(balance)
if earlier is None: first_seen[balance] = i else: length = i - earlier if length > best: best = length return best
💬 class Solution: def pivotIndex(self, nums: list[int]) -> int: """Return the leftmost index with equal sums on either side, or -1.
The pivot itself is excluded from both sums. At either end of the array, the empty side has a sum of zero. """ # loop nums for O(n) while keep track for left_sum left_sum = 0 right_sum = sum(nums) for i in range(len(nums)): right_sum -= nums[i] if left_sum == right_sum: return i else: left_sum += nums[i]
💬 class Solution: def maxArea(self, height: list[int]) -> int: if not height: return 0 # area = (right - left) * min ( height[right], height[left]) left = 0 right = len(height) - 1 max_area = 0 while left < right: area = (right - left) * min(height[right], height[left]) if area > max_area: max_area = area # move shorter inward if height[left] > height[right]: right = right - 1 else: left = left + 1 return max_area