Lists Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Test your mastery of Python lists with fundamental technical coding round problems frequently asked in placement exams.
Finding the second largest element in O(N)
Track the largest and second largest values in a single pass without sorting.
nums = [12, 35, 1, 10, 34, 1]first = second = float('-inf')for x in nums: if x > first: second = first first = x elif x > second and x != first: second = xprint(f"Second largest: {second}")Example 1 · Largest value and where it is
sales = [120, 340, 90, 340, 15]top = max(sales)print(top)print(sales.index(top))print(sales.count(top))340 1 2
What this code does
maxfinds the biggest value in one pass.indexgives the first position of that value, andcountsays it appears twice.
This single-pass algorithm operates in O(N) time and O(1) space, outperforming O(N log N) sorting.
List rotation by K steps
Rotate a list by k steps using slice concatenation.
nums = [1, 2, 3, 4, 5]k = 2k = k % len(nums)rotated = nums[-k:] + nums[:-k]print(f"Rotated by {k}: {rotated}")Example 2 · Removing repeats from a sorted list
arr = [1, 1, 2, 2, 3, 4, 4]# Remove duplicates preserving orderunique = []for x in arr: if not unique or unique[-1] != x: unique.append(x)print("Unique items:", unique)Unique items: [1, 2, 3, 4]
What this code does
- Iterates through sorted array.
- Appends element only if it differs from the last added element.
- Produces clean unique list
[1, 2, 3, 4].
Example 3 · Running totals
daily = [5, 3, 8, 2]running = []total = 0for amount in daily: total += amount running.append(total)print(running)[5, 8, 16, 18]
What this code does
- Each round adds the new amount to
totaland stores the result. - The new list is built item by item, so
dailyis never changed.
Slicing nums[-2:] gives [4, 5], and nums[:-2] gives [1, 2, 3]. Concatenating them produces [4, 5, 1, 2, 3].
Finish up
Mark complete & continue
Next: Must-do problems: Lists