Table of contents
No headings in the article.
Open the Problem on LeetCode:
- Navigate to the problem on LeetCode, such as "Contains Duplicate."
Understand the Problem Statement:
Read the problem description carefully.
For example, in "Contains Duplicate," the question states:
"Given an integer arraynums
, returntrue
if any value appears at least twice in the array, and returnfalse
if every element is distinct."Simplify this in your own words:
- "We are given an integer array called
nums
. We need to check if the array contains any duplicate values. If it does, returntrue
; otherwise, returnfalse
."
- "We are given an integer array called
Examine the Examples for Clarity:
Look at the examples provided in the problem to better understand the requirement:
Example 1:
Input:
nums = [1, 2, 3, 1]
Output:
true
Explanation: The number
1
appears twice, at indices0
and3
.
Based on this example, you understand that the task is to find duplicates and return
true
if duplicates exist; otherwise, returnfalse
.
Analyze the Constraints:
Review the constraints to determine the input size and range of values:
Example Constraints:
1 <= nums.length <= 10^5
: The array can contain up to 100,000 elements.-10^9 <= nums[i] <= 10^9
: Each element in the array is within the range of -1 billion to 1 billion.
Use these constraints to decide:
Should you write a brute-force solution or aim for an optimized approach?
Since the array size can go up to 1 lakh, a brute-force O(n2)O(n^2)O(n2) solution will exceed the time limit. Therefore, you should aim for an O(n)O(n)O(n) or O(nlogn)O(n \log n)O(nlogn) solution.
Plan the Solution:
Now that you understand the problem, examples, and constraints:
Think of a clear plan or algorithm to solve the problem efficiently.
For this example:
- Use a HashSet to track numbers you've seen before. If you encounter a number that's already in the set, return
true
. If you finish checking the array without finding duplicates, returnfalse
.
- Use a HashSet to track numbers you've seen before. If you encounter a number that's already in the set, return
Write and Test Your Code:
Write the code for your solution.
Test it against the provided examples and edge cases to ensure it works correctly.