Lesson 4 of 7 · 15 min · 1 hands-on step

Functions & Problem Solving

A repeatable method for solving problems you've never seen before.

Functions in Python

Python · try it
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Ada")             # "Hello, Ada!"
greet("Ada", "Welcome")  # "Welcome, Ada!"

Default parameter values (greeting="Hello") make functions flexible without extra code.

A method for any problem

Interviewers care more about how you solve a problem than whether you've memorized it. Use the same five steps every time:

  1. Restate the problem in your own words.
  2. Examples: work through 2–3 inputs by hand, including edge cases (empty, one item, duplicates, negatives).
  3. Plan: describe the approach in plain words, and its Big-O, before coding.
  4. Code: write it cleanly, with good names.
  5. Test: walk through your examples and fix what breaks.

Make it work, then make it better

Start with the simplest correct solution, even if it's slow:

Python · try it
def second_largest(nums):
    distinct = sorted(set(nums))
    return distinct[-2] if len(distinct) >= 2 else None

Then improve it: this version is O(n log n) because it sorts. Can you make it O(n)? Saying this out loud in an interview ("here's a working version, now let me optimize") is exactly what interviewers want to hear.

🧪 Practice

Write second_largest(nums) that returns the second-largest distinct value in a list.

  • second_largest([4, 1, 9, 7]) → 7
  • second_largest([5, 5, 3]) → 3
  • If there is no second distinct value, return None

Bonus: can you do it in a single pass, without sorting?

Python
def second_largest(nums):
    # 1. Restate the problem  2. Try examples  3. Plan  4. Code  5. Test edge cases
    pass

print(second_largest([4, 1, 9, 7]))

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What does a Python function return if it has no return statement?

  2. In an interview, what should you do before writing code?

Create a free account to track your progress.