TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
nums
.Q: What is the expected output of the function?
nums
that are smaller than the respective element.Q: How is the count determined?
nums[i]
, count how many elements nums[j]
(where j != i
) are smaller than nums[i]
.Q: Can there be duplicate elements in nums
?
nums
can contain duplicate elements.Q: What if the list is empty?
-The function smaller_than_current()
should take a list of integers, nums, and return a list where each element represents the count of numbers in nums that are smaller than the corresponding element, excluding itself.
HAPPY CASE
Input: [8, 1, 2, 2, 3]
Expected Output: [4, 0, 1, 1, 3]
Input: [6, 5, 4, 8]
Expected Output: [2, 1, 0, 3]
EDGE CASE
Input: [7, 7, 7, 7]
Expected Output: [0, 0, 0, 0]
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the list using nested loops to compare each element with all other elements to count how many are smaller.
1. Initialize an empty list `result`.
2. For each index `i` in `nums`, do the following:
- Initialize a counter `count` to 0.
- For each index `j` in `nums`, check if `j` is not equal to `i` and if `nums[j]` is smaller than `nums[i]`.
- If true, increment `count`.
- Append `count` to `result`.
3. Return `result`
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def smaller_than_current(nums):
result = []
for i in range(len(nums)):
count = 0
for j in range(len(nums)):
if nums[j] < nums[i]:
count += 1
result.append(count)
return result