Easy DSA Questions — Arrays and Basic Problem Solving
Start with fundamental DSA problems involving arrays, loops, conditions, counting, searching, and simple transformations. These questions build the problem-solving patterns required for more advanced algorithms.
01. Find the Largest Element in an Array
Given an array of numbers, find the largest element.
How It Works & Algorithmic Design
To find the maximum element without sorting, we use a Single-Pass Linear Scan pattern.
- Initialization: Assume the first element (
arr[0]) is the largest seen so far. Storing an element from the array ensures that negative numbers or zero values do not break the comparison logic (unlike initializing to0). - Iteration: Loop through each remaining element from left to right.
- Comparison & Update: For every element, check if it is strictly greater than our current maximum variable (
max). If it is, overwritemaxwith the new value. - Edge Case Handling: If the input array is empty (
arr.length === 0), there is no valid maximum; returnnullor an equivalent empty-state value.
Why This Approach Works Best
Alternative approaches like sorting the array first take $O(n \log n)$ time complexity. This iterative scan inspects every element exactly once, giving an optimal linear $O(n)$ runtime while using $O(1)$ constant auxiliary memory.
Specifications & Requirements
Returns null immediately
Exactly n - 1 comparisons for n elements
Example Walkthrough 1
[4, 8, 2, 10, 3]
Unsorted array with positive integers.
Init: max=4 | Check 8 -> max=8 | Check 2 -> max=8 | Check 10 -> max=10 | Check 3 -> max=10
Tracks the running maximum state across iterations.
10
10 is the largest value in the array.
Example Walkthrough 2 (Negative Numbers)
[-15, -3, -45, -8]
Array containing only negative values.
-3
Initializing with arr[0] (-15) correctly allows -3 to be chosen as max.
Answer: Find maximum element
function largest(arr) {
if (!arr || arr.length === 0) return null;
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}Iterate through the array sequentially and maintain a tracking variable initialized to the first element.
Always initialize the tracking variable with an actual element from the array (like
arr[0]), not0or arbitrary values.A single pass linear scan inspects every element once, providing $O(n)$ time complexity.
No dynamic memory allocation is required, giving $O(1)$ constant space complexity.
02. Find the Smallest Element in an Array
Given an array of numbers, locate and return the smallest element.
How It Works & Algorithmic Design
Finding the minimum value uses the exact inverse logic of finding the maximum value:
- Initialization: Set
min = arr[0]. This establishes a benchmark value present inside the input dataset. - Linear Pass: Loop through the array from index
1toarr.length - 1. - Conditional Update: Compare each element with
min. If the current value is strictly lower (arr[i] < min), updatemin = arr[i]. - Completion: Once all $n$ elements are evaluated,
minholds the smallest value.
Why This Approach Works Best
This algorithm requires no sorting or external memory data structures. It evaluates the array in $O(n)$ time while operating in-place ($O(1)$ space).
Example Walkthrough
[12, 5, 25, 1, 9]
Unsorted numbers including positive integers.
Init: min=12 | Check 5 -> min=5 | Check 25 -> min=5 | Check 1 -> min=1 | Check 9 -> min=1
Updates 'min' whenever a strictly smaller value is found.
1
1 is the smallest element in the input list.
Answer: Find minimum element
function smallest(arr) {
if (!arr || arr.length === 0) return null;
let min = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
}
return min;
}Traverse the array sequentially and retain the lowest value encountered.
Reversing the comparison operator (
<instead of>) turns maximum-finding into minimum-finding.Linear traversal inspects all items in $O(n)$ time.
Always account for empty inputs before referencing index
0to prevent runtime exceptions.
03. Calculate the Sum of Array Elements
Compute the sum of all numerical values in a given array.
How It Works & Algorithmic Design
This utilizes the Accumulator Pattern:
- State Initialization: Declare an accumulator variable
total = 0. Zero acts as the additive identity element ($x + 0 = x$). - Iteration: Walk through the elements one by one.
- Accumulation: Add each element's value to
totalusing the addition assignment operator (total += element). - Return: Once the loop completes, return
total.
Why This Approach Works Best
It performs a single pass over the array with constant extra space ($O(1)$ memory). For large arrays, integer overflow should be considered depending on the language (e.g., using 64-bit integers like long in Java when working with large numbers).
Example Walkthrough
[1, 2, 3, 4, 5]
Sequential numbers from 1 to 5.
0 + 1 = 1 | 1 + 2 = 3 | 3 + 3 = 6 | 6 + 4 = 10 | 10 + 5 = 15
Accumulates values step by step.
15
Total sum of all elements.
Answer: Calculate total sum
function sum(arr) {
let total = 0;
for (const value of arr) {
total += value;
}
return total;
}Iterate through the array and accumulate values into a tracking variable.
Initialize accumulators with the identity element (
0for sum,1for product).Time complexity is $O(n)$ as every element is visited once.
In languages like Java or C++, use
longto prevent overflow when dealing with large numbers.
04. Count Even Numbers in an Array
Determine the count of even numbers contained in an array.
How It Works & Algorithmic Design
This combines Conditional Filtering with Counter Incrementation:
- Divisibility Condition: A integer $x$ is defined as even if $x \pmod 2 = 0$.
- Counter Setup: Initialize
count = 0. - Evaluation Loop: Traverse through each number in the array. Apply the modulo operator (
value % 2). If the remainder equals0, incrementcountby 1. - Negative Numbers: The condition
value % 2 === 0holds true for negative even integers as well (e.g.,-4 % 2 === 0), making this approach robust across integer domains.
Why This Approach Works Best
It processes the input in $O(n)$ runtime and $O(1)$ extra space without creating intermediate filtered arrays in memory.
Example Walkthrough
[1, 4, 7, 8, 10, 13]
Mixed odd and even integers.
1 (Odd) -> 4 (Even, count=1) -> 7 (Odd) -> 8 (Even, count=2) -> 10 (Even, count=3) -> 13 (Odd)
Only increments counter when number % 2 == 0.
3
There are three even numbers (4, 8, 10).
Answer: Count even values
function countEven(arr) {
let count = 0;
for (const value of arr) {
if (value % 2 === 0) count++;
}
return count;
}Filter numbers using modulo 2 and increment a counter variable.
Modulo operator (
%) accurately checks for divisibility.Avoid instantiating auxiliary filtered arrays to keep space complexity at $O(1)$.
Modulo operation works consistently for both positive and negative even integers.
05. Reverse an Array In-Place
Reverse the order of elements in an array without using extra memory allocations.
How It Works & Algorithmic Design
This demonstrates the Two Pointers Technique:
- Pointer Setup: Position a
leftpointer at index0and arightpointer at indexarr.length - 1. - Symmetric Swapping: While
left < right:- Swap the elements at
arr[left]andarr[right]. - Increment
left(left++). - Decrement
right(right--).
- Swap the elements at
- Termination: When
left >= right, the pointers meet or cross in the middle, confirming all elements have been mirrored.
Why This Approach Works Best
Creating a duplicate reversed array requires $O(n)$ auxiliary space. The two-pointer in-place swap modifies the original array directly, achieving $O(n/2) = O(n)$ time complexity and true $O(1)$ space complexity.
Example Walkthrough
[10, 20, 30, 40, 50]
Original array.
Swap index 0 (10) & 4 (50) -> [50, 20, 30, 40, 10]
left=1, right=3.
Swap index 1 (20) & 3 (40) -> [50, 40, 30, 20, 10]
left=2, right=2. Loop terminates.
[50, 40, 30, 20, 10]
Array reversed in place.
Answer: Reverse in-place using two pointers
function reverse(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}Swap symmetric elements from opposite ends using converging pointers.
Two-pointer technique avoids extra memory overhead.
Only $n/2$ iterations are needed to reverse an array of size $n$.
In-place algorithm design modifies the input reference directly.
06. Check Whether an Array Is Sorted
Verify if an array's elements are ordered in non-decreasing sequence ($arr[i] \le arr[i+1]$).
How It Works & Algorithmic Design
This uses an Adjacent Pair Comparison strategy with Early Termination:
- Invariant: An array is sorted if every consecutive pair satisfied $arr[i - 1] \le arr[i]$.
- Iteration: Start looping from index
1up toarr.length - 1. - Violation Check: Compare
arr[i]against its preceding neighborarr[i - 1]. Ifarr[i] < arr[i - 1], a sorting violation has occurred. Instantly returnfalse. - Success Return: If the loop finishes without finding any out-of-order pair, return
true.
Why This Approach Works Best
It avoids checking $O(n^2)$ pairs by relying on transitivity: if $a \le b$ and $b \le c$, then $a \le c$. Comparing adjacent items in a single pass ($O(n)$ time, $O(1)$ space) is sufficient.
Example Walkthrough 1 (Sorted)
[2, 5, 8, 8, 12]
Non-decreasing array containing a duplicate.
5 >= 2 (OK) -> 8 >= 5 (OK) -> 8 >= 8 (OK) -> 12 >= 8 (OK)
No violation found.
true
Array is sorted.
Example Walkthrough 2 (Unsorted)
[1, 3, 2, 4]
Unsorted array.
3 >= 1 (OK) -> 2 < 3 (VIOLATION!)
Returns false immediately at index 2.
false
Array is not sorted.
Answer: Check array order
function isSorted(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) return false;
}
return true;
}Scan adjacent elements and return false upon detecting any out-of-order pair.
Transitivity property allows order verification through adjacent comparisons alone.
Early return optimizes average runtime when input arrays are unsorted.
Single-pass linear scan yields optimal $O(n)$ time performance.
07. Linear Search
Search for a specific target value within an unsorted array and return its index.
How It Works & Algorithmic Design
Linear Search inspects elements sequentially from beginning to end:
- Sequential Traversal: Loop over the array using index $i$ from $0$ to $n-1$.
- Match Evaluation: Compare
arr[i] === target. If equal, return index $i$ immediately. - Failure Case: If the iteration reaches the end of the array without a match, return
-1to signal the element was not found.
Why This Approach Works Best
When an array is unsorted, no assumptions can be made about element placement. Every position must be checked in the worst case, making linear search the optimal strategy ($O(n)$ time, $O(1)$ space) without pre-sorting.
Example Walkthrough
[15, 8, 42, 4, 23]
Target to search for: 42.
arr[0]=15 (No) -> arr[1]=8 (No) -> arr[2]=42 (MATCH!)
Finds element at index 2.
2
Index where target is located.
Answer: Linear Search implementation
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}Inspect array elements sequentially and return the matching index.
Linear search works on both sorted and unsorted collections.
Worst-case performance is $O(n)$ when the target is absent or located at the end.
Returns index immediately on first match, achieving best-case $O(1)$ runtime.
08. Count Occurrences of a Target
Find how many times a given target value appears within an array.
How It Works & Algorithmic Design
Unlike Linear Search (which returns early upon finding the first match), counting occurrences requires inspecting every element in the array:
- Counter Initialization: Set
count = 0. - Exhaustive Pass: Iterate through every position from index $0$ to $n-1$.
- Match Accumulation: Increment
countby $1$ every timearr[i] === target. - Final Result: Return the accumulated total after the loop finishes.
Why This Approach Works Best
Because target matches may occur multiple times across the array, early termination cannot be used. Inspecting every element gives a time complexity of $O(n)$ and $O(1)$ space.
Example Walkthrough
[5, 2, 5, 8, 5, 1], Target: 5
Target number 5 appears multiple times.
5 (count=1) -> 2 -> 5 (count=2) -> 8 -> 5 (count=3) -> 1
Evaluates all elements sequentially.
3
Number 5 appears 3 times.
Answer: Count target frequencies
function countOccurrences(arr, target) {
let count = 0;
for (const value of arr) {
if (value === target) count++;
}
return count;
}Scan the entire collection and increment a counter whenever the value matches.
Requires an exhaustive scan over the entire collection.
Runs in $O(n)$ time while keeping memory overhead at $O(1)$.
Can be extended to count frequencies across multiple targets using a Hash Map.
09. Find the Second Largest Element
Find the second largest distinct element in an array without sorting.
How It Works & Algorithmic Design
This uses a Dual-Variable Tracking approach in a single pass:
- Variables: Maintain
first(largest) andsecond(second largest), initialized to negative infinity (-Infinity). - Iteration & Rules: Loop through each number $x$:
- Case 1 ($x > first$): A new maximum is found. Demote the old
firsttosecond(second = first), then updatefirst = x. - Case 2 ($x > second$ and $x < first$): $x$ is not the largest, but is strictly greater than
second. Updatesecond = x. - Case 3 ($x \le second$): Ignore $x$.
- Case 1 ($x > first$): A new maximum is found. Demote the old
- Distinct Constraint: The check
x < firstin Case 2 ensures duplicates of the maximum value do not improperly overwritesecond. - Result: If
secondremains-Infinity, no distinct second largest element exists; returnnull.
Why This Approach Works Best
Sorting takes $O(n \log n)$ time. Scanning twice (once for max, once for second max) takes $O(2n)$ time. This dual-variable method finds the answer in a single $O(n)$ pass using $O(1)$ memory.
Example Walkthrough
[12, 35, 1, 10, 34, 1]
Unsorted array with distinct elements.
Check 12 (first=12) -> Check 35 (second=12, first=35) -> Check 1 -> Check 10 -> Check 34 (second=34) -> Check 1
Tracks both top distinct values simultaneously.
34
34 is the second largest distinct element.
Answer: Find second largest distinct element
function secondLargest(arr) {
let first = -Infinity;
let second = -Infinity;
for (const x of arr) {
if (x > first) {
second = first;
first = x;
} else if (x > second && x < first) {
second = x;
}
}
return second === -Infinity ? null : second;
}Track the top two distinct maximum values simultaneously in one traversal.
Demote
firsttosecondwhenever a new maximum is found.Ensure duplicates of the max value do not overwrite
secondby checkingx < first.Solves the problem in a single pass ($O(n)$ time) without extra space ($O(1)$ memory).
10. Remove Duplicates from a Sorted Array
Given a sorted array, remove duplicate values in place such that each unique element appears only once. Return the number of unique elements.
How It Works & Algorithmic Design
This problem uses a Read/Write Two-Pointer Pattern:
- Precondition: Because the array is sorted, all duplicate elements are contiguous.
- Pointer Definitions:
write: Index where the next unique value should be placed (starts at1).read: Index used to scan through the array (starts at1).
- Scanning Logic: Compare
arr[read]with the element right before it (arr[read - 1]):- If
arr[read] !== arr[read - 1], a new unique element has been found. - Write this unique element to
arr[write], then incrementwrite(write++).
- If
- Result: The value of
writeequals the total count of unique elements, and the sub-arrayarr[0 ... write - 1]contains those unique values in order.
Why This Approach Works Best
It modifies the array in-place without creating a new set or duplicate array, running in $O(n)$ time and $O(1)$ extra space.
Example Walkthrough
[0, 0, 1, 1, 1, 2, 2, 3]
Sorted array with duplicate groups.
arr[1]=1 -> arr[2]=2 -> arr[3]=3
Overwrites duplicate positions with newly discovered unique values.
[0, 1, 2, 3, ...]
Unique elements shifted to the front.
4
4 unique elements found.
Answer: In-place deduplication
function removeDuplicates(arr) {
if (!arr || arr.length === 0) return 0;
let write = 1;
for (let read = 1; read < arr.length; read++) {
if (arr[read] !== arr[read - 1]) {
arr[write] = arr[read];
write++;
}
}
return write;
}Use read and write pointers to overwrite duplicate entries in a single pass.
Contiguous grouping in sorted arrays makes duplicate detection straightforward.
The read pointer scans elements while the write pointer places unique values.
Achieves $O(n)$ time complexity and $O(1)$ space complexity by modifying the array in-place.
11. Count Odd Numbers in an Array
Given an array of integers, count how many values are odd.
How It Works & Algorithmic Design
An integer is odd when dividing it by 2 leaves a remainder of 1 or -1. We can detect this using the modulo operator:
- Initialize
count = 0. - Traverse every element in the array.
- Check whether
value % 2 !== 0. - If the condition is true, increment
count. - Return the final count.
Why This Approach Works Best
Every element must be inspected once, giving $O(n)$ time complexity. Only one counter is required, so the auxiliary space is $O(1)$.
Example Walkthrough
[2, 5, 7, 8, 11, 14]
The array contains both even and odd numbers.
2 -> Even | 5 -> Odd | 7 -> Odd | 8 -> Even | 11 -> Odd | 14 -> Even
Only odd values increase the counter.
3
The odd numbers are 5, 7, and 11.
Answer: Count odd values
function countOdd(arr) {
let count = 0;
for (const value of arr) {
if (value % 2 !== 0) count++;
}
return count;
}Traverse the array and use modulo 2 to determine whether each number is odd.
The modulo operator helps determine whether an integer is odd or even.
Every element must be checked, so the time complexity is O(n).
Only a counter is required, giving O(1) auxiliary space.
12. Calculate the Average of Array Elements
Given an array of numbers, calculate the average of all elements.
How It Works & Algorithmic Design
The average is calculated as sum / count:
- Initialize a
sumvariable to0. - Traverse every element and add it to
sum. - After traversal, divide
sumby the number of elements. - Handle an empty array separately because division by zero is invalid.
Why This Approach Works Best
The array only needs to be traversed once. The algorithm requires $O(n)$ time and $O(1)$ auxiliary space.
Example Walkthrough
[10, 20, 30, 40]
Four numerical values are provided.
10 + 20 + 30 + 40 = 100
All values are accumulated.
25
Average = 100 / 4 = 25.
Answer: Calculate array average
function average(arr) {
if (arr.length === 0) return null;
let sum = 0;
for (const value of arr) {
sum += value;
}
return sum / arr.length;
}First calculate the total sum and then divide it by the number of elements.
Average is calculated as total sum divided by number of elements.
Always handle an empty array before dividing.
The algorithm runs in O(n) time and O(1) space.
13. Find the Index of the Largest Element
Given an array of numbers, find the index of the largest element.
How It Works & Algorithmic Design
Instead of storing only the maximum value, maintain the index where the maximum occurs:
- Start with
maxIndex = 0. - Compare each element with
arr[maxIndex]. - If a larger element is found, update
maxIndex. - Return the index after completing the scan.
- Return
-1for an empty array.
Why This Approach Works Best
A single linear traversal is enough. The algorithm requires $O(n)$ time and $O(1)$ auxiliary space.
Example Walkthrough
[10, 4, 25, 7, 18]
The largest value is 25.
maxIndex=0 -> 2
When 25 is encountered, its index becomes the new maximum index.
2
The largest element is located at index 2.
Answer: Find index of maximum
function largestIndex(arr) {
if (!arr.length) return -1;
let maxIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}Track the index of the largest value instead of only storing the value.
Store the index rather than only the maximum value.
Comparing against arr[maxIndex] avoids maintaining two separate pieces of state.
The solution uses O(n) time and O(1) space.
14. Find the Index of the Smallest Element
Given an array of numbers, find the index of the smallest element.
How It Works & Algorithmic Design
Use the same tracking pattern as maximum-index search, but compare for smaller values:
- Initialize
minIndex = 0. - Traverse the remaining elements.
- If
arr[i] < arr[minIndex], updateminIndex. - Return
minIndex. - Return
-1if the array is empty.
Why This Approach Works Best
No sorting is required. One pass gives $O(n)$ time with $O(1)$ extra space.
Example Walkthrough
[8, 3, 12, 1, 6]
The smallest value is 1.
minIndex=0 -> 1 -> 3
The index changes whenever a smaller value is discovered.
3
The smallest element is at index 3.
Answer: Find index of minimum
function smallestIndex(arr) {
if (!arr.length) return -1;
let minIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return minIndex;
}Maintain the index of the smallest value encountered during the traversal.
Track the index of the smallest element instead of only the value.
Initialize the index using the first valid element.
The algorithm runs in O(n) time and O(1) space.
15. Count Positive, Negative, and Zero Values
Given an array of integers, count how many values are positive, negative, and zero.
How It Works & Algorithmic Design
Each value belongs to exactly one of three categories:
- If
value > 0, increment the positive counter. - If
value < 0, increment the negative counter. - Otherwise, increment the zero counter.
- Return all three counts.
Why This Approach Works Best
A single traversal classifies every element. The algorithm uses $O(n)$ time and $O(1)$ auxiliary space.
Example Walkthrough
[-3, 5, 0, 8, -2, 0]
The array contains all three possible categories.
Positive=2 | Negative=2 | Zero=2
Each number increments exactly one counter.
{ positive: 2, negative: 2, zero: 2 }
The three counters represent the classification.
Answer: Count number categories
function countTypes(arr) {
let positive = 0;
let negative = 0;
let zero = 0;
for (const value of arr) {
if (value > 0) positive++;
else if (value < 0) negative++;
else zero++;
}
return { positive, negative, zero };
}Use three counters and classify each value using conditional comparisons.
Use mutually exclusive conditions when every value belongs to exactly one category.
Three counters are sufficient for this problem.
The solution requires O(n) time and O(1) space.
16. Separate Even and Odd Numbers
Given an array of integers, create two collections containing the even and odd numbers separately.
How It Works & Algorithmic Design
Traverse the input once:
- Create an empty collection for even numbers.
- Create an empty collection for odd numbers.
- For every value, use
value % 2to determine its category. - Add the value to the corresponding collection.
- Return both collections.
Why This Approach Works Best
Every element is inspected once. Because the output itself can contain up to $n$ elements, the auxiliary/output space is $O(n)$.
Example Walkthrough
[1, 4, 7, 8, 10, 13]
Mixed even and odd values.
Even=[4,8,10] | Odd=[1,7,13]
Each number is placed into exactly one output collection.
Answer: Separate even and odd values
function separateEvenOdd(arr) {
const even = [];
const odd = [];
for (const value of arr) {
if (value % 2 === 0) even.push(value);
else odd.push(value);
}
return { even, odd };
}Create two output arrays and classify each number using modulo.
Modulo provides a simple way to classify even and odd numbers.
Every input value is visited exactly once.
The output arrays require O(n) space in the worst case.
17. Find the Second Smallest Element
Find the second smallest distinct element in an array without sorting it.
How It Works & Algorithmic Design
Maintain two values: the smallest and second smallest:
- Initialize both to positive infinity.
- For each value, if it is smaller than the current smallest, move the smallest value into second smallest.
- Otherwise, if it is greater than the smallest but smaller than the second smallest, update second smallest.
- Return
nullif a distinct second smallest value does not exist.
Why This Approach Works Best
Sorting would require $O(n \log n)$ time. Tracking two values allows a single $O(n)$ traversal with $O(1)$ extra space.
Example Walkthrough
[8, 3, 5, 1, 4]
The smallest value is 1 and the second smallest distinct value is 3.
smallest=1 | secondSmallest=3
The two smallest distinct values are tracked during one traversal.
3
3 is the second smallest distinct value.
Answer: Find second smallest
function secondSmallest(arr) {
let first = Infinity;
let second = Infinity;
for (const x of arr) {
if (x < first) {
second = first;
first = x;
} else if (x > first && x < second) {
second = x;
}
}
return second === Infinity ? null : second;
}Track the two smallest distinct values during a single traversal.
Track the two smallest distinct values instead of sorting.
The condition x > first prevents duplicate minimum values from becoming second smallest.
The algorithm runs in O(n) time and O(1) space.
18. Copy an Array Without Using Built-in Copy Methods
Create a new array containing the same elements as the input array without using built-in array copy methods.
How It Works & Algorithmic Design
Use direct traversal:
- Create an empty result array.
- Visit every element of the source array.
- Add each value to the result array.
- Return the newly created array.
Why This Approach Works Best
The operation demonstrates basic array traversal and explicit construction. Since a new array containing all $n$ elements is created, the space complexity is $O(n)$.
Example Walkthrough
[10, 20, 30]
The source array contains three values.
result=[] -> [10] -> [10,20] -> [10,20,30]
Each source element is manually added to the new array.
[10, 20, 30]
The returned array contains the same values but is a separate array.
Answer: Manually copy an array
function copyArray(arr) {
const result = [];
for (const value of arr) {
result.push(value);
}
return result;
}Create a new array and copy each element one by one.
Manual copying demonstrates basic traversal and array construction.
The original array remains unchanged.
Creating a new array requires O(n) additional space.
19. Find the Difference Between Maximum and Minimum
Given an array of numbers, find the difference between the largest and smallest values.
How It Works & Algorithmic Design
Instead of sorting the array:
- Track the maximum value.
- Track the minimum value.
- Traverse the array once and update both when necessary.
- Return
max - min. - Handle an empty array appropriately.
Why This Approach Works Best
Sorting is unnecessary. Both extremes can be found in one pass, resulting in $O(n)$ time and $O(1)$ auxiliary space.
Example Walkthrough
[4, 10, 2, 8, 15]
Maximum is 15 and minimum is 2.
15 - 2 = 13
Subtract the smallest value from the largest value.
13
The range between the minimum and maximum is 13.
Answer: Find max-min difference
function maxMinDifference(arr) {
if (!arr.length) return null;
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
return max - min;
}Track both extremes during one traversal and subtract them at the end.
Maximum and minimum can be found simultaneously.
Sorting is unnecessary for calculating the range.
The algorithm requires O(n) time and O(1) auxiliary space.
20. Check if an Array Contains a Given Element
Given an array and a target value, determine whether the target exists in the array.
How It Works & Algorithmic Design
Use a basic linear search:
- Traverse the array from left to right.
- Compare every value with the target.
- Return
trueimmediately when a match is found. - If the loop completes without finding the target, return
false.
Why This Approach Works Best
For an unsorted array, there is no information that allows us to skip arbitrary positions. Linear search provides $O(n)$ worst-case time and $O(1)$ auxiliary space.
Example Walkthrough
[5, 8, 12, 3, 20], Target=12
The target exists in the array.
5 -> 8 -> 12
The search stops as soon as 12 is found.
true
The target exists at index 2.
Answer: Check whether target exists
function contains(arr, target) {
for (const value of arr) {
if (value === target) return true;
}
return false;
}Use linear search and return immediately when the target is found.
Linear search can answer existence questions directly.
Early return avoids unnecessary comparisons when the target is found.
Worst-case time is O(n), while auxiliary space is O(1).