10 Essential LeetCode Problems for Beginners: Brute Force vs. Optimal Solutions in Java
A complete beginner's guide to understanding the problem, tracing the code, learning the algorithm, and analyzing Big O complexity.
// TABLE OF CONTENTS+
A complete beginner's guide to understanding the problem, tracing the code, learning the algorithm, and analyzing Big O complexity.
- Category: Data Structures and Algorithms (DSA)
- Language: Java
- Level: Beginner
- Problems covered: Two Sum, Valid Anagram, Contains Duplicate, Valid Palindrome, LCM, Missing Number, Single Number, Fizz Buzz, GCD, and Happy Number
Introduction: How to actually learn DSA
Imagine you have a box full of numbers. Someone asks you to find two numbers that add up to 10.
You could pick the first number, compare it with every other number, then pick the second number and repeat the process. Eventually, you might find the answer.
That approach works. But what happens when the box contains a million numbers?
You need a better strategy.
This is the fundamental idea behind Data Structures and Algorithms. You start with a method that works, understand how it behaves, identify unnecessary work, and improve it.
LeetCode is useful for learning this skill because its problems force you to think about correctness, efficiency, and edge cases.
However, beginners often make one mistake: they memorize the final solution without understanding why it works.
For example, you might memorize this line:
result ^= num;But if you do not understand XOR, you will struggle to explain why it solves Single Number or recognize where the same technique applies elsewhere.
The objective of this guide is different. For each problem, we will examine:
- What the question means in simple language.
- An example that makes the problem concrete.
- The brute-force approach and how it works.
- A step-by-step walkthrough of the brute-force code.
- Why the brute-force approach becomes inefficient.
- The optimal approach and the idea behind it.
- A detailed walkthrough of the optimal Java code.
- Time complexity and auxiliary space complexity.
- Edge cases and common mistakes.
- What you should remember for future problems.
All solutions use Java. Each code snippet is intended to be submitted as the corresponding LeetCode Solution method unless otherwise stated. The methods for GCD and LCM are standalone examples because those are mathematical warm-up exercises rather than standard problems in the same LeetCode format.
Before the problems: Understand Big O notation
Big O notation describes how an algorithm's work grows as its input becomes larger.
Suppose an array contains 10 numbers. An algorithm might perform 10 operations, 100 operations, or 1,000 operations depending on its approach.
Now imagine the array contains 10,000 numbers. The difference between algorithms can become enormous.
The five common complexity classes
| Complexity | Simple explanation | Example |
|---|---|---|
| O(1) | Work stays approximately constant | One array index lookup |
| O(log n) | The problem shrinks rapidly | Binary search |
| O(n) | Work grows with the input size | One pass through an array |
| O(n log n) | More work than linear, less than quadratic | Efficient comparison sorting |
| O(n²) | Work can grow like the square of the input size | Comparing every pair |
Consider an array with \(n=1{,}000\) elements.
- O(1) means a constant number of operations.
- O(n) means work proportional to about 1,000 elements.
- O(n²) means work proportional to about 1,000,000 pairs.
These are simplified illustrations, not exact runtime measurements. Actual execution time depends on implementation, hardware, and other factors.
What does O(1) space mean?
Space complexity is about memory, not speed.
Consider this code:
int sum = 0;
for (int num : nums) {
sum += num;
}The algorithm uses only one extra variable, sum. Its auxiliary space is O(1).
However, it still visits every number. Its time complexity is O(n).
Remember: O(1) auxiliary space does not mean O(1) time.
We will use this distinction throughout the article.
Problem 1: Two Sum
1.1 Understand the question
You are given an array of integers and a target number.
Your job is to find two different elements whose sum equals the target and return their indices.
An index is the position of an element in an array. In Java, array indexing starts at zero.
Consider this array:
int[] nums = {2, 7, 11, 15};
int target = 9;The numbers 2 and 7 add up to 9.
Their indices are 0 and 1, so the answer is:
[0, 1]Notice something important: the problem asks for indices, not the actual values.
Returning [2, 7] would be incorrect even though those numbers add up to 9.
Also, you cannot use the same array element twice. If the array contains one number equal to 5 and the target is 10, you cannot use that single element twice unless the array contains another 5.
1.2 Brute-force solution
The simplest idea is to try every possible pair.
Take the first element and compare it with all the elements after it. Then take the second element and compare it with the remaining elements. Continue until you find a pair that adds up to the target.
Java code
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[]{};
}
}Understand every important line
Line 1:
for (int i = 0; i < nums.length; i++)This chooses the first element.
If the array contains four elements, i takes the values 0, 1, 2, and 3.
Line 2:
for (int j = i + 1; j < nums.length; j++)This chooses the second element.
Why start at i + 1 rather than zero?
Because we only want pairs of different elements, and we do not need to check the same pair twice.
For example, the pair (2, 7) is the same pair as (7, 2) for this problem. Once we have considered it, considering it again adds no value.
Line 3:
if (nums[i] + nums[j] == target)This checks whether the selected pair has the required sum.
Line 4:
return new int[]{i, j};If the sum matches, return the two indices immediately.
Trace the brute-force solution
Input:
nums = [2, 7, 11, 15]
target = 9| First index `i` | Second index `j` | Calculation | Result |
|---|---|---|---|
| 0 | 1 | 2 + 7 = 9 | Found |
The algorithm returns [0, 1] and stops.
Now consider:
nums = [1, 4, 6, 8]
target = 14The algorithm tests the pairs:
- 1 + 4
- 1 + 6
- 1 + 8
- 4 + 6
- 4 + 8
- 6 + 8
None equals 14, so the algorithm returns an empty array.
Complexity of brute force
- Time: O(n²)
- Auxiliary space: O(1)
Why O(n²)?
The outer loop selects each element. For each selection, the inner loop examines the remaining elements.
The number of comparisons is approximately:
\[ \frac{n(n-1)}{2} \]
Ignoring constants and smaller terms gives O(n²).
The algorithm uses only a few variables, so its auxiliary space is O(1).
1.3 Optimal solution: HashMap
The brute-force approach repeatedly searches for a matching number.
Can we remember what we have already seen?
Yes. Java's HashMap allows us to store a number and its index.
For every number, we calculate the number needed to reach the target.
For example:
target = 9;
num = 2;The required complement is:
9 - 2 = 7If we have already encountered 7, we have our answer.
Otherwise, we store 2 and its index and continue.
Java code
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[]{seen.get(complement), i};
}
seen.put(nums[i], i);
}
return new int[]{};
}
}Understand the HashMap
A HashMap stores key-value pairs.
In this solution:
- The key is the number.
- The value is its index.
For example, after processing the number 2 at index 0, the map contains:
2 -> 0This means the number 2 appeared at index 0.
Trace the optimal solution
Input:
nums = [2, 7, 11, 15]
target = 9First iteration:
i = 0
nums[i] = 2
complement = 9 - 2 = 7The map is empty. We have not seen 7.
Store the current number:
Map: {2=0}Second iteration:
i = 1
nums[i] = 7
complement = 9 - 7 = 2The map already contains 2 at index 0.
Return:
[0, 1]We have found the answer without examining every possible pair.
Why must we check before inserting?
Suppose:
nums = [3];
target = 6;The algorithm must not use the same element twice.
By checking the map before inserting the current number, the algorithm only matches against an earlier element. That preserves the requirement for two distinct indices.
Complexity of the optimal solution
- Time: O(n) average
- Auxiliary space: O(n)
We traverse the array once. HashMap lookups and insertions are O(1) on average under normal hashing assumptions.
The map may store nearly every element, so it requires O(n) additional space.
What to remember
Use a HashMap when you repeatedly need to answer questions such as:
- Have I seen this value?
- At what index did this value appear?
- What number would complete the required sum?
Two Sum is a foundational example of trading extra memory for faster searching.
Problem 2: Valid Anagram
2.1 Understand the question
An anagram is a word or string made by rearranging the characters of another word or string.
For example:
listen
silentBoth contain:
- One l
- One i
- One s
- One t
- One e
- One n
The character order is different, but the characters and their frequencies are identical.
Therefore, the answer is true.
Now compare:
hello
worldThese strings contain different characters and frequencies, so the answer is false.
The key idea is that character order does not matter, but character frequency does.
2.2 Brute-force solution: Sorting
If two strings are anagrams, sorting their characters produces the same ordered sequence.
For example:
listen -> eilnst
silent -> eilnstWe can sort both strings and compare them.
Java code
import java.util.Arrays;
class Solution {
public boolean isAnagram(String s, String t) {
char[] first = s.toCharArray();
char[] second = t.toCharArray();
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}
}How it works
Step 1: Convert strings into character arrays.
char[] first = s.toCharArray();
char[] second = t.toCharArray();Java strings are immutable. toCharArray() creates arrays that can be sorted.
Step 2: Sort both arrays.
Arrays.sort(first);
Arrays.sort(second);For example:
"listen" -> ['e', 'i', 'l', 'n', 's', 't']
"silent" -> ['e', 'i', 'l', 'n', 's', 't']Step 3: Compare the arrays.
return Arrays.equals(first, second);If the characters match at every position, the arrays are equal.
Complexity
- Time: O(n log n)
- Auxiliary space: O(n) for the character arrays, excluding sorting's internal workspace
Sorting dominates the time complexity. The method also allocates arrays containing the characters of both strings.
A useful improvement
If the strings have different lengths, they cannot be anagrams.
We can check that first:
if (s.length() != t.length()) {
return false;
}This avoids unnecessary work for strings whose lengths differ.
2.3 Optimal solution: Character frequency counting
Sorting works, but it does more work than necessary.
Imagine you have two bags of letter tiles. You do not need to arrange every tile alphabetically. You only need to count the tiles in each bag.
The same principle applies here.
If both strings contain exactly the same number of each character, they are anagrams.
For lowercase English letters, we only need 26 counters.
Java code
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] frequency = new int[26];
for (int i = 0; i < s.length(); i++) {
frequency[s.charAt(i) - 'a']++;
frequency[t.charAt(i) - 'a']--;
}
for (int count : frequency) {
if (count != 0) {
return false;
}
}
return true;
}
}Understand the frequency array
int[] frequency = new int[26];This creates 26 integers, one for each lowercase English letter.
The letter a corresponds to index 0, b to index 1, and z to index 25.
Java lets us calculate the index using:
s.charAt(i) - 'a'For lowercase English letters, subtracting 'a' converts the character into a number from 0 through 25.
Why increment and decrement?
frequency[s.charAt(i) - 'a']++;
frequency[t.charAt(i) - 'a']--;For every character in the first string, increase its counter.
For every character in the second string, decrease its counter.
If both strings contain the same number of each character, every counter will eventually return to zero.
Trace the algorithm
Input:
s = "ab"
t = "ba"Initially:
a: 0
b: 0Process the first position:
- a in the first string increments the a counter.
- b in the second string decrements the b counter.
The counters become:
a: 1
b: -1Process the second position:
- b in the first string increments the b counter.
- a in the second string decrements the a counter.
The counters become:
a: 0
b: 0All counters are zero, so the strings are anagrams.
Now consider:
s = "ab"
t = "aa"After processing both strings:
a: 0
b: 1The b counter is not zero. Therefore, the strings are not anagrams.
Complexity
- Time: O(n)
- Auxiliary space: O(1)
We process the characters and then examine 26 counters. Since 26 is fixed, the frequency array uses constant auxiliary space.
This implementation assumes lowercase English letters. For arbitrary Unicode text, a more general frequency map or code-point-aware implementation is needed.
What to remember
When the order of elements does not matter but their counts do, consider frequency counting before sorting.
This technique appears in anagrams, character-frequency questions, and many counting problems.
Problem 3: Contains Duplicate
3.1 Understand the question
You are given an array and must determine whether any number appears more than once.
Example:
int[] nums = {1, 2, 3, 1};The number 1 appears twice.
The answer is true.
Now consider:
int[] nums = {1, 2, 3, 4};Every number is unique, so the answer is false.
The task does not ask which number is duplicated or how many times it occurs. It only asks whether a duplicate exists.
3.2 Brute-force solution
Compare each element with every element after it.
class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}How it works
The outer loop chooses one number.
The inner loop checks whether that number appears again later in the array.
For this input:
[1, 2, 3, 1]The comparisons begin with:
1 vs 2 -> different
1 vs 3 -> different
1 vs 1 -> equalThe method immediately returns true.
If no matching pair exists, the method returns false after examining all pairs.
Complexity
- Time: O(n²)
- Auxiliary space: O(1)
The nested loops create a quadratic number of possible comparisons in the worst case.
The algorithm does not create an additional collection.
3.3 Optimal solution: HashSet
Instead of comparing every pair, remember the values that have already appeared.
A Java HashSet stores unique values.
Before adding a number, check whether the set already contains it. Java's Set.add() method makes this convenient because it returns false when the element is already present.
Java code
import java.util.HashSet;
import java.util.Set;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
return true;
}
}
return false;
}
}Trace the solution
Input:
[1, 2, 3, 1]Initially:
seen = {}Process 1:
Add 1
seen = {1}Process 2:
Add 2
seen = {1, 2}Process 3:
Add 3
seen = {1, 2, 3}Process the final 1:
1 is already presentThe add() operation returns false, and the method returns true.
Complexity
- Time: O(n) average
- Auxiliary space: O(n)
In the worst case, the set may contain nearly every number in the array.
Can we make it shorter?
Yes:
return nums.length !=
new HashSet<Integer>() {{
for (int num : nums) add(num);
}}.size();However, this uses an unnecessary anonymous inner class and is not a good style choice for beginners.
The explicit loop is clearer and can stop as soon as a duplicate is found.
What to remember
A set is useful when you need to know whether a value has appeared before.
The same technique can solve problems involving repeated words, duplicate IDs, and unique elements.
Problem 4: Valid Palindrome
4.1 Understand the question
A palindrome reads the same forward and backward.
Examples:
racecar
level
madamLeetCode's Valid Palindrome problem adds two rules:
- Ignore punctuation, spaces, and other non-alphanumeric characters.
- Ignore uppercase versus lowercase.
Therefore:
A man, a plan, a canal: Panamais a palindrome because the meaningful characters become:
amanaplanacanalpanamaThe cleaned sequence reads identically in both directions.
4.2 Brute-force solution
The simplest method is to build a new string containing only letters and digits, convert the letters to lowercase, reverse the string, and compare the two versions.
Java code
class Solution {
public boolean isPalindrome(String s) {
StringBuilder cleaned = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isLetterOrDigit(ch)) {
cleaned.append(Character.toLowerCase(ch));
}
}
String value = cleaned.toString();
String reversed = new StringBuilder(value)
.reverse()
.toString();
return value.equals(reversed);
}
}Understand the steps
Step 1: Create an empty builder.
StringBuilder cleaned = new StringBuilder();A StringBuilder lets us append characters efficiently.
Step 2: Examine each character.
char ch = s.charAt(i);This retrieves the character at position i.
Step 3: Ignore punctuation and spaces.
if (Character.isLetterOrDigit(ch))This condition accepts letters and digits.
Step 4: Convert the character to lowercase and append it.
cleaned.append(Character.toLowerCase(ch));For example, A becomes a, while a comma is skipped.
Step 5: Reverse and compare.
return value.equals(reversed);If the cleaned string equals its reverse, it is a palindrome.
Complexity
- Time: O(n)
- Auxiliary space: O(n)
We inspect each character and construct additional strings.
4.3 Optimal solution: Two pointers
Can we check the palindrome without creating another string?
Yes.
Imagine two people reading the same word. One starts from the left, and the other starts from the right. They move toward each other and compare the characters.
If a meaningful pair differs, the string is not a palindrome.
Java code
class Solution {
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
while (left < right &&
!Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (left < right &&
!Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (Character.toLowerCase(s.charAt(left)) !=
Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}Understand the pointers
int left = 0;
int right = s.length() - 1;The left pointer begins at the first character. The right pointer begins at the last character.
The loop continues while the pointers have not crossed.
Why skip characters?
Suppose the string is:
A, b, aThe comma is not a letter or digit. It should not affect the result.
The inner loops move the pointers past punctuation and spaces until they reach relevant characters.
Why compare lowercase characters?
Character.toLowerCase(s.charAt(left))This ensures that A and a are treated as equivalent.
Trace a mismatch
Consider:
"hello"The outer characters are:
h vs oThey differ, so the algorithm returns false immediately.
There is no need to inspect the remaining characters.
Complexity
- Time: O(n)
- Auxiliary space: O(1)
Each pointer moves in one direction through the original string. No additional string is needed.
Important: Java's char represents a UTF-16 code unit. This implementation follows the usual character-based LeetCode approach, but it does not implement full Unicode grapheme-cluster comparison.
What to remember
Two pointers can reduce memory usage even when they do not improve time complexity.
This pattern is especially useful when comparing opposite ends of an array or string.
Problem 5: Lowest Common Multiple (LCM)
5.1 Understand the question
The least common multiple is the smallest positive number that is divisible by two given positive integers.
Suppose the inputs are 4 and 6.
Multiples of 4:
4, 8, 12, 16, 20, 24, ...Multiples of 6:
6, 12, 18, 24, ...The first common positive multiple is 12.
Therefore:
LCM(4, 6) = 12LCM is a useful mathematical warm-up, although it is not one of the standard ten LeetCode problems in the same format as Two Sum.
5.2 Brute-force solution
Start with the larger input and keep checking larger numbers until one is divisible by both.
Java code
public static long lcmBrute(long a, long b) {
if (a == 0 || b == 0) {
return 0;
}
a = Math.abs(a);
b = Math.abs(b);
long candidate = Math.max(a, b);
while (candidate % a != 0 ||
candidate % b != 0) {
candidate++;
}
return candidate;
}This example defines the LCM involving zero as zero, which is a common programming convention. It assumes the result and intermediate candidates fit in long.
Trace the algorithm
Inputs:
a = 4
b = 6Start with:
candidate = 6Check:
6 % 4 != 0Six is not divisible by four.
Try 7, then 8, then 9, then 10, then 11.
At 12:
12 % 4 == 0
12 % 6 == 0The algorithm returns 12.
Complexity
- Time: O(LCM(a, b)) as a loose upper bound on candidate checks
- Auxiliary space: O(1)
The number of candidates actually tested depends on the starting point and the LCM. This is not a tight bound, but it illustrates why repeated candidate testing can be inefficient.
5.3 Optimal solution: Use GCD
The GCD is the greatest common divisor: the largest positive integer that divides both inputs.
For example:
GCD(12, 18) = 6The LCM and GCD are connected by this identity:
\[ \operatorname{LCM}(a,b) = \frac{|a|}{\operatorname{GCD}(a,b)}\times |b| \]
Instead of searching for the LCM, calculate the GCD and use the formula.
Java code
public static long gcd(long a, long b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
long remainder = a % b;
a = b;
b = remainder;
}
return a;
}
public static long lcm(long a, long b) {
if (a == 0 || b == 0) {
return 0;
}
return Math.abs((a / gcd(a, b)) * b);
}Trace the calculation
Inputs:
a = 12
b = 18First calculate the GCD.
18 % 12 = 6
12 % 6 = 0Therefore:
GCD(12, 18) = 6Now use the LCM formula:
LCM = (12 / 6) * 18
= 2 * 18
= 36The result is 36.
Complexity
- Time: O(log(min(|a|, |b|))) for nonzero inputs
- Auxiliary space: O(1)
The Euclidean algorithm reduces the inputs quickly, rather than checking successive multiples.
Java detail: For the full long range, Math.abs(Long.MIN_VALUE) is still negative because its positive counterpart cannot be represented. The multiplication can also overflow. Production code that must handle unrestricted integer ranges needs explicit overflow handling.
What to remember
When a number problem looks like a search, check whether a mathematical identity can replace that search.
Problem 6: Missing Number
6.1 Understand the question
You receive an array containing distinct numbers from 0 through n. Exactly one number from that range is missing.
Example:
int[] nums = {3, 0, 1};The expected range is:
0, 1, 2, 3The array contains 0, 1, and 3.
The missing number is 2.
The array may be unordered, so you cannot assume the numbers appear in numerical order.
6.2 Brute-force solution
Check every expected number against every array element.
Java code
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
for (int candidate = 0; candidate <= n; candidate++) {
boolean found = false;
for (int num : nums) {
if (num == candidate) {
found = true;
break;
}
}
if (!found) {
return candidate;
}
}
return -1;
}
}Understand the algorithm
The array length is 3, so the complete range must be 0 through 3.
First, look for 0. It exists.
Next, look for 1. It exists.
Next, look for 2. It does not exist.
The algorithm returns 2.
Why is it inefficient?
For every candidate, the algorithm may inspect the entire array.
If the missing number is near the end of the range, the algorithm performs many comparisons.
- Time: O(n²)
- Auxiliary space: O(1)
6.3 Optimal solution: Mathematical sum
There is a simple formula for the sum of the first n positive integers:
\[ 1+2+\cdots+n=\frac{n(n+1)}{2} \]
For the complete range from 0 through n, the formula remains the same because adding zero does not change the sum.
Therefore:
Missing number = Expected sum - Actual sumJava code
class Solution {
public int missingNumber(int[] nums) {
long n = nums.length;
long expectedSum = n * (n + 1) / 2;
long actualSum = 0;
for (int num : nums) {
actualSum += num;
}
return (int) (expectedSum - actualSum);
}
}Trace the solution
Input:
[3, 0, 1]The array length is 3.
Calculate the expected sum:
3 * (3 + 1) / 2
= 3 * 4 / 2
= 6Calculate the actual sum:
3 + 0 + 1 = 4Subtract:
6 - 4 = 2The missing number is 2.
Complexity
- Time: O(n)
- Auxiliary space: O(1)
The algorithm still needs to inspect the input to calculate its actual sum, so it cannot solve an arbitrary unsummarized array in constant time.
Alternative: XOR
Another solution uses XOR to cancel out matching numbers. It also achieves O(n) time and O(1) auxiliary space, and avoids the risk of arithmetic-sum overflow.
What to remember
When an array contains a complete range except for one missing element, look for a mathematical invariant rather than searching for every candidate.
Problem 7: Single Number
7.1 Understand the question
Every number in the array appears exactly twice, except for one number that appears only once.
Find that unique number.
Example:
int[] nums = {4, 1, 2, 1, 2};The number 1 appears twice.
The number 2 appears twice.
The number 4 appears once.
The answer is 4.
The guarantee about duplicate pairs is essential. The XOR solution relies on it.
7.2 Brute-force solution
Count the occurrences of each number. When a number appears exactly once, return it.
Java code
class Solution {
public int singleNumber(int[] nums) {
for (int num : nums) {
int count = 0;
for (int other : nums) {
if (num == other) {
count++;
}
}
if (count == 1) {
return num;
}
}
return -1;
}
}Trace the algorithm
For the number 4:
Compare 4 with every element.
Only one element equals 4.
count = 1The algorithm returns 4.
If the unique value appears later in the array, the algorithm may repeat many comparisons before finding it.
- Time: O(n²)
- Auxiliary space: O(1)
7.3 Optimal solution: XOR
XOR is a bitwise operation in Java, written using ^.
It compares the binary digits of two numbers.
The two most important properties are:
x ^ x = 0
x ^ 0 = xIn simple terms, XORing a number with itself cancels it out. XORing a number with zero leaves the number unchanged.
Because XOR is associative and commutative, the order of the numbers does not affect the final result.
Java code
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}Trace the solution
Input:
[4, 1, 2, 1, 2]Start with:
result = 0Process 4:
0 ^ 4 = 4Process 1:
4 ^ 1Process 2:
4 ^ 1 ^ 2Process the next 1:
4 ^ 1 ^ 2 ^ 1The two occurrences of 1 cancel:
1 ^ 1 = 0Process the final 2. The two occurrences of 2 also cancel.
The only remaining value is:
4Complexity
- Time: O(n)
- Auxiliary space: O(1)
The algorithm makes one pass through the array and uses one accumulator.
Why this is better than a HashMap
A HashMap could count how often every number appears, but it would need additional memory.
XOR solves this particular problem without a map because the input guarantees that duplicates occur in pairs.
What to remember
Bitwise techniques are most useful when a problem provides a mathematical guarantee that allows values to cancel or combine in a predictable way.
If numbers appeared three times instead of twice, this exact solution would not work.
Problem 8: Fizz Buzz
8.1 Understand the question
Fizz Buzz is a simple problem about applying rules to a sequence of numbers.
For every integer from 1 through n:
- If the number is divisible by both 3 and 5, output "FizzBuzz".
- Otherwise, if divisible by 3, output "Fizz".
- Otherwise, if divisible by 5, output "Buzz".
- Otherwise, output the number as a string.
For n = 5, the result is:
["1", "2", "Fizz", "4", "Buzz"]For n = 15, the last value is "FizzBuzz".
A number is divisible by another number when the remainder is zero. In Java, the remainder operator is %.
For example:
15 % 3 == 0
15 % 5 == 0Both conditions are true.
8.2 Straightforward solution
Java code
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) {
result.add("FizzBuzz");
} else if (i % 3 == 0) {
result.add("Fizz");
} else if (i % 5 == 0) {
result.add("Buzz");
} else {
result.add(String.valueOf(i));
}
}
return result;
}
}Understand the code
The list stores the answers:
List<String> result = new ArrayList<>();The loop visits each number:
for (int i = 1; i <= n; i++)The conditions decide what to add.
Why check divisibility by 15 first?
Because 15 is divisible by both 3 and 5.
If we checked only divisibility by 3 first, then 15 would produce "Fizz" and the algorithm would never reach the "FizzBuzz" condition.
Checking the combined condition first avoids that mistake.
Finally:
result.add(String.valueOf(i));converts an ordinary number to a string.
Complexity
- Time: O(n)
- Output space: O(n)
The algorithm must generate n results. Therefore, linear time is asymptotically optimal.
8.3 Alternative solution: Build the output string
We can also construct the result from the conditions that apply.
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
StringBuilder value = new StringBuilder();
if (i % 3 == 0) {
value.append("Fizz");
}
if (i % 5 == 0) {
value.append("Buzz");
}
if (value.length() == 0) {
value.append(i);
}
result.add(value.toString());
}
return result;
}
}For 15, the first condition adds "Fizz" and the second adds "Buzz". Together, they produce "FizzBuzz".
Is this solution faster?
Not asymptotically.
Both implementations run in O(n) time and require O(n) output space.
This is an important lesson: sometimes the straightforward solution is already optimal in Big O terms.
What to remember
Learn how to order conditional statements correctly and recognize when a problem has an unavoidable lower bound because every output must be generated.
Problem 9: Greatest Common Divisor (GCD)
9.1 Understand the question
The greatest common divisor is the largest positive integer that divides two numbers exactly.
For example, the divisors of 12 are:
1, 2, 3, 4, 6, 12The divisors of 18 are:
1, 2, 3, 6, 9, 18Their common divisors are:
1, 2, 3, 6The largest common divisor is 6.
Therefore:
GCD(12, 18) = 69.2 Brute-force solution
Start with the smaller absolute input and test each candidate divisor, working downward.
Java code
public static long gcdBrute(long a, long b) {
a = Math.abs(a);
b = Math.abs(b);
for (long divisor = Math.min(a, b);
divisor >= 1;
divisor--) {
if (a % divisor == 0 &&
b % divisor == 0) {
return divisor;
}
}
return 0;
}Why start with the smaller number?
A common divisor cannot be larger than either input.
If the numbers are 12 and 18, there is no reason to test 18 as a divisor of 12. We can begin at 12.
The first candidate that divides both numbers is guaranteed to be the largest common divisor because we are testing from largest to smallest.
Trace the algorithm
Inputs:
a = 12
b = 18Test 12:
18 % 12 != 0It is not a common divisor.
Test 11, 10, 9, and so on.
When we reach 6:
12 % 6 == 0
18 % 6 == 0The algorithm returns 6.
Complexity
- Time: O(min(|a|, |b|))
- Auxiliary space: O(1)
The algorithm can test a number of candidates proportional to the smaller input.
9.3 Optimal solution: Euclidean algorithm
The Euclidean algorithm uses a remarkable property:
\[ \gcd(a,b)=\gcd(b,a\bmod b) \]
The remainder operation allows us to replace the original pair with a smaller pair without changing the GCD.
Java code
public static long gcd(long a, long b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
long remainder = a % b;
a = b;
b = remainder;
}
return a;
}This method returns the nonnegative GCD, with the conventional result gcd(0, 0) = 0.
Trace the algorithm
Start with:
a = 48
b = 18First iteration:
remainder = 48 % 18 = 12
a = 18
b = 12Second iteration:
remainder = 18 % 12 = 6
a = 12
b = 6Third iteration:
remainder = 12 % 6 = 0
a = 6
b = 0The loop stops because b is zero.
The method returns 6.
Why does this work?
The common divisors of a and b are exactly the common divisors of b and the remainder of a divided by b.
This allows us to reduce the problem repeatedly without losing the answer.
Complexity
- Time: O(log(min(|a|, |b|))) for nonzero inputs
- Auxiliary space: O(1)
The values shrink quickly, so the algorithm requires far fewer iterations than testing every possible divisor.
What to remember
GCD is a useful example of a mathematical problem where a better algorithm comes from understanding a property of the numbers, rather than selecting a more complicated data structure.
Problem 10: Happy Number
10.1 Understand the question
A happy number is a positive integer that eventually becomes 1 when you repeatedly replace it with the sum of the squares of its digits.
For example, take 19.
Square each digit and add the results:
1² + 9² = 82Repeat with 82:
8² + 2² = 68Repeat with 68:
6² + 8² = 100Repeat with 100:
1² + 0² + 0² = 1The sequence reaches 1, so 19 is a happy number.
What if the sequence never reaches 1?
For a positive integer, the process eventually repeats a value and enters a cycle. Once it repeats, it will keep following the same cycle rather than discovering a new value that leads to 1.
This gives us two possibilities:
- The sequence reaches 1.
- The sequence enters a cycle without reaching 1.
10.2 Brute-force solution: HashSet
The easiest way to detect a cycle is to remember every number we have already seen.
If the next number is already in the set, we know the process has repeated.
Java code
import java.util.HashSet;
import java.util.Set;
class Solution {
private int nextNumber(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = nextNumber(n);
}
return n == 1;
}
}Understand the helper method
private int nextNumber(int n)This method calculates the sum of the squares of the digits.
Consider 19.
int digit = n % 10;The remainder when dividing 19 by 10 is 9, so the last digit is 9.
Then:
sum += digit * digit;
n /= 10;We add \(9^2\) and remove the last digit using integer division. The remaining number is 1.
The next iteration processes 1.
The final sum is:
81 + 1 = 82Therefore, nextNumber(19) returns 82.
Understand the main method
The set stores previously visited numbers.
while (n != 1 && !seen.contains(n))Continue while the current value is not 1 and has not appeared before.
Inside the loop:
seen.add(n);
n = nextNumber(n);Remember the current number and calculate the next one.
If the loop stops, the number either reached 1 or repeated a previous value.
The final line:
return n == 1;returns true only when the sequence reached 1.
Complexity
Let k be the number of states visited and d be the maximum number of digits processed per state.
- Time: O(k · d)
- Auxiliary space: O(k)
The set stores the visited states. This is easy to understand, but it consumes additional memory.
10.3 Optimal solution: Floyd's cycle detection
Can we detect the cycle without storing every previous number?
Yes. We can use two pointers moving through the sequence at different speeds.
Imagine two runners on a circular track. One moves one step at a time, while the other moves two steps at a time. If both are on the same cycle, the faster runner eventually catches the slower one.
The same principle applies here.
Java code
class Solution {
private int nextNumber(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
int slow = n;
int fast = nextNumber(n);
while (fast != 1 && slow != fast) {
slow = nextNumber(slow);
fast = nextNumber(nextNumber(fast));
}
return fast == 1;
}
}Understand the two pointers
The slow pointer moves one step:
slow = nextNumber(slow);The fast pointer moves two steps:
fast = nextNumber(nextNumber(fast));If the sequence reaches 1, the fast pointer reaches 1.
If the sequence enters a cycle, the two pointers eventually meet.
Trace the algorithm
Start with 19:
slow = 19
fast = 82First iteration:
slow = 82
fast = 68Second iteration:
slow = 68
fast = 1The fast pointer reaches 1, so the method returns true.
Complexity
- Time: O(k · d), where k is the number of states traversed and d is the maximum number of digits processed per state
- Auxiliary space: O(1)
The algorithm avoids the set and uses only two pointers and a helper method.
What to remember
Cycle detection is useful when a process repeatedly transforms a value and eventually either terminates or repeats.
This pattern also appears in linked-list cycle detection and other problems involving deterministic sequences.
Final comparison: All ten problems
The table below summarizes the main approaches and their complexities.
| # | Problem | Brute-force time | Improved time | Improved auxiliary space |
|---|---|---|---|---|
| 1 | Two Sum | O(n²) | O(n) average | O(n) |
| 2 | Valid Anagram | O(n log n) | O(n) | O(1) for 26 letters |
| 3 | Contains Duplicate | O(n²) | O(n) average | O(n) |
| 4 | Valid Palindrome | O(n) | O(n) | O(1) |
| 6 | Missing Number | O(n²) | O(n) | O(1) |
| 7 | Single Number | O(n²) | O(n) | O(1) |
| 8 | Fizz Buzz | O(n) | O(n) | O(n) output |
| 10 | Happy Number | O(k · d) | O(k · d) | O(1) |
Here, n is the array or string length, k represents visited states for Happy Number, and d is the maximum number of digits processed per state.
A key observation is that not every improved solution reduces the time complexity. Valid Palindrome remains O(n) but uses less auxiliary memory. Fizz Buzz is already asymptotically optimal because it must produce n outputs.
How to practice these problems without memorizing everything
For each problem, follow this process:
Step 1: Explain the problem in plain English.
If you cannot explain the question without reading it, you probably do not fully understand it yet.
Step 2: Work through a small example by hand.
Write down the input, the state of your variables, and the expected output.
Step 3: Implement the brute-force solution.
Do not skip this stage. It helps you understand the direct approach and gives you something to improve.
Step 4: Identify the repeated work.
Ask yourself:
- Am I searching the same array repeatedly?
- Can I remember previous values?
- Does the order of the data matter?
- Is there a mathematical property I can use?
- Can two pointers avoid allocating another collection?
- Is a repeated process entering a cycle?
Step 5: Implement the improved solution.
Choose the technique that matches the problem rather than forcing every problem into the same pattern.
Step 6: Analyze both time and space.
Do not stop at saying that one solution is faster. Explain why it is faster and what additional memory it requires.
Step 7: Test edge cases.
Examples include an empty array where permitted, a single-element array, negative numbers where allowed, repeated values, strings containing only punctuation, and the smallest valid inputs.
Step 8: Explain the solution without reading the code.
If you can explain what every variable represents, why each loop exists, and why the algorithm must return the correct answer, you understand the problem much more deeply than someone who has only memorized the implementation.
Conclusion
These ten problems introduce several foundational techniques in data structures and algorithms:
- HashMap for efficient lookups.
- HashSet for detecting duplicates and visited states.
- Frequency counting for character comparisons.
- Two pointers for comparing opposite ends of a sequence.
- Mathematical identities for number problems.
- XOR for cancelling duplicate pairs.
- Euclidean GCD for efficient divisor calculations.
- Floyd's algorithm for cycle detection.
The main lesson is not that every problem needs a clever trick. It is that the best algorithm depends on the problem's structure, guarantees, and constraints.
Sometimes you trade memory for speed. Sometimes mathematics eliminates a search. Sometimes the straightforward solution is already optimal.
Learn the reasoning behind each technique, practise tracing the code, and then try implementing the solution without looking. That is how these ten beginner problems become a foundation for much harder DSA questions.
SEO details
SEO title: 10 LeetCode Problems for Beginners in Java: Brute Force vs. Optimal Solutions
Meta description: Learn 10 beginner LeetCode problems with detailed Java solutions, step-by-step examples, brute-force and optimal approaches, Big O complexity, and DSA patterns explained simply.
Suggested URL slug: leetcode-beginner-problems-java-brute-force-optimal
Primary keyword: LeetCode problems for beginners in Java
Related keywords: Java DSA tutorial, brute force vs optimal algorithms, LeetCode Java solutions, Big O notation explained, beginner coding interview problems, Java data structures and algorithms.
Suggested article category: Data Structures & Algorithms
Suggested tags: Java, LeetCode, DSA, Algorithms, Coding Interviews, Big O Notation, Beginners
OPEN
Thoughts on the article.