Complete the code to calculate the sum of numbers from 1 to n efficiently in O(1) time.
def sum_to_n(n): return n * (n [1] 1) // 2 print(sum_to_n(5))
The formula n * (n + 1) // 2 computes the triangular number sum in constant O(1) time, faster than an O(n) loop for large n.
Complete the O(n) code to find the largest number in the list (linear scan).
numbers = [3, 7, 2, 9, 5] max_num = numbers[0] for num in numbers: if num [1] max_num: max_num = num print(max_num)
A single loop scans the list once (O(n) time), efficient for finding the maximum without sorting O(n log n).
Complete the slow O(n^2) nested loop code to check for duplicates.
def has_duplicate(nums): for i in range(len(nums)): for j in range([1], len(nums)): if nums[i] == nums[j]: return True return False print(has_duplicate([1,2,2,3]))
Nested loops compare each pair (O(n^2) time), slow for large lists. Starting j at i+1 avoids self-comparison.
Complete the fast O(n) code using a set to check for duplicates.
def has_duplicate_fast(nums): seen = set() for num in nums: if num [1] seen: return True seen.[2](num) return False print(has_duplicate_fast([1,2,2,3]))
Sets provide O(1) average lookup/add, making the whole algorithm O(n), much faster than O(n^2) nested loops.
Fill blanks for O(n) dict comprehension to map words to lengths (efficient single pass).
words = ['apple', 'bat', 'carrot', 'dog'] lengths = {word: [1] for word in words if len(word) [2] 3} print(lengths)
Dict comprehension processes each word once O(n), faster in practice than equivalent loop with if checks.