Skip to content

Smaller Than

Raymond Chen edited this page Aug 1, 2024 · 6 revisions

TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Arrays, Nested Loops

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?

-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]

P-lan

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

  • Forgetting to exclude the current element when counting.
  • Off-by-one errors when accessing list indices.

I-mplement

Implement the code to solve the algorithm.

def print_catchphrase(character):
    if character == ""Pooh"":
        print(""Oh bother!"")
    elif character == ""Tigger"":
        print(""TTFN: Ta-ta for now!"")
    elif character == ""Eeyore"":
        print(""Thanks for noticing me."")
    elif character == ""Christopher Robin"":
        print(""Silly old bear."")
    else:
        print(f""Sorry! I don't know {character}'s catchphrase!"")
Clone this wiki locally