C++ Fundamentals

Lesson 04 · 16 min

Functions, Classes & Pass-by-Reference

How LeetCode Solution classes work, and why we pass vectors by reference.

Functions & the Solution class

Pass by value vs reference

void f(vector<int> a);        // COPY — slow for big arrays
void g(vector<int>& a);       // reference — can modify caller's vector
void h(const vector<int>& a); // read-only borrow — preferred for input

LeetCode often gives vector<int>& nums so you may modify in-place (Move Zeroes, Rotate).

Solution class pattern

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // your logic
        return {};
    }
};

Methods are usually public. Helper functions can be private inside the same class.

Return types

Match the problem: int, bool, vector<int>, string, ListNode*, …

Wrong return type = compile error — read the signature twice before coding.

Rules to remember

  • Big inputs: pass const T& unless you must mutate.
  • In-place problems: mutate the reference parameter.
  • Match the exact return type in the signature.
  • Helpers: private methods keep Solution clean.

Check yourself

1. Best signature for read-only array input?

Practice what you learned