Easy DSA Questions — Strings, Numbers, and Basic Algorithms
Continue with beginner-friendly problems involving strings, digits, comparisons, transformations, and simple mathematical reasoning.
01. Reverse a String
Reverse a given input string.
How It Works & Algorithmic Design
Strings can be processed using either Built-In Language Methods or an In-Place Two-Pointer Character Array Swap:
- Two-Pointer Approach: Convert the string into a mutable character array. Place
left = 0andright = length - 1. Swap characters while incrementingleftand decrementingrightuntil they meet in the middle. - Language Idioms: Languages like Python (
s[::-1]) or Java (StringBuilder.reverse()) offer optimized native operations.
Why This Approach Works Best
Both methods run in linear time $O(n)$. Understanding the manual pointer-swap mechanism is essential for interviews, especially when working with languages that treat strings as immutable.
Example Walkthrough
"hello"
5-character string.
'h' <-> 'o' => "oellh" -> 'e' <-> 'l' => "olleh"
Swaps characters from outside inward.
"olleh"
Reversed string.
Answer: Reverse string implementations
function reverseString(s) {
return s.split('').reverse().join('');
}Demonstrates built-in helpers and low-level character array transformations.
String immutability in languages like Java, JS, and Python requires allocating a new string ($O(n)$ space).
The underlying algorithm relies on the converging two-pointer swap pattern.
Linear time complexity $O(n)$ is needed to process all $n$ characters.
02. Check Whether a String Is a Palindrome
Determine whether a string reads the same forward and backward.
How It Works & Algorithmic Design
This uses the Symmetric Two-Pointer Check:
- Pointer Positions: Set
left = 0andright = s.length - 1. - Symmetry Test: Compare
s[left]ands[right]:- If
s[left] !== s[right], the string is not symmetrical. Immediately returnfalse. - Otherwise, advance
left++and retreatright--toward the middle.
- If
- Completion: If pointers cross (
left >= right) without a character mismatch, returntrue.
Why This Approach Works Best
Rather than reversing the entire string (which takes extra space and time), this method checks characters in-place and stops early on the first mismatch. It processes at most $n/2$ comparisons, achieving $O(n)$ time and $O(1)$ extra space.
Example Walkthrough 1 (Palindrome)
"racecar"
Odd-length palindrome string.
'r'=='r' -> 'a'=='a' -> 'c'=='c' -> Center reached ('e')
All symmetric character pairs match.
true
String is a valid palindrome.
Example Walkthrough 2 (Non-Palindrome)
"hello"
Non-palindrome string.
'h' != 'o' (Mismatch found instantly)
Terminates on the first comparison.
false
String is not a palindrome.
Answer: Two-pointer palindrome check
function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) return false;
left++;
right--;
}
return true;
}Compare symmetric characters from both ends moving inward toward the center.
Checks symmetry using two converging pointers.
Early termination avoids unnecessary comparisons when a mismatch is found.
Operates in $O(n)$ time and $O(1)$ extra space.
03. Count Vowels in a String
Count the number of vowels (a, e, i, o, u - case insensitive) in a given string.
How It Works & Algorithmic Design
This applies Set-Based Lookups within a Linear Character Pass:
- Vowel Set Lookup: Store target vowels (
aeiouAEIOU) in a Hash Set or string lookup table. Checking existence in a Hash Set takes constant time ($O(1)$). - Counting Loop: Iterate over every character
chin the string. - Evaluation: If
vowelSet.has(ch), incrementcount++. - Return: Return the accumulated count.
Why This Approach Works Best
Using a set lookup avoids writing long if-else condition chains. The linear traversal processes the string in $O(n)$ time complexity while requiring only $O(1)$ auxiliary space for the fixed 10-character vowel set.
Example Walkthrough
"Algorithm"
Mixed case string.
'A' (Yes, count=1) -> 'o' (Yes, count=2) -> 'i' (Yes, count=3)
Matches 'A', 'o', and 'i'.
3
Contains 3 vowels.
Answer: Count vowels using set lookup
function countVowels(s) {
const vowels = new Set('aeiouAEIOU');
let count = 0;
for (const ch of s) {
if (vowels.has(ch)) count++;
}
return count;
}Inspect characters against a fixed vowel set and accumulate matching counts.
Hash Set lookups take $O(1)$ constant time.
Case sensitivity should be handled by including both uppercase and lowercase vowels in the set.
Runs in $O(n)$ linear time relative to string length.
04. Find the Frequency of Each Character
Construct a frequency table mapping each character in a string to its total number of occurrences.
How It Works & Algorithmic Design
This relies on Hash Map Frequency Counting:
- Hash Map Setup: Initialize an empty key-value Hash Map
freqMap. - Character Scanning: Iterate through each character
chin the string. - Map Update:
- If
chexists as a key infreqMap, increment its associated value (freqMap[ch] + 1). - If
chis not infreqMap, insert it with an initial value of1(freqMap[ch] = 1).
- If
- Result: Return the populated frequency map.
Why This Approach Works Best
Hash Map insertions and lookups take $O(1)$ average time. Scanning the string of length $n$ takes $O(n)$ time. The space complexity is $O(k)$, where $k$ is the number of unique characters in the alphabet (at most $O(1)$ for fixed character sets like ASCII or lowercase English letters).
Example Walkthrough
"banana"
6-character string with repeating letters.
'b': 1 -> 'a': 1 -> 'n': 1 -> 'a': 2 -> 'n': 2 -> 'a': 3
Updates key counts as characters are scanned.
{ 'b': 1, 'a': 3, 'n': 2 }
Final counts for each unique character.
Answer: Build character frequency table
function charFrequency(s) {
const freq = {};
for (const ch of s) {
freq[ch] = (freq[ch] || 0) + 1;
}
return freq;
}Populate a Hash Map by using characters as keys and their counts as values.
Hash Maps provide average $O(1)$ insertion and lookup times for frequency counting.
Frequency maps serve as building blocks for solving complex string problems like Anagram Detection.
Time complexity is $O(n)$, and space complexity is bounded by the size of the unique character set ($O(k)$).
05. Check if Two Strings are Anagrams
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
How It Works & Algorithmic Design
An anagram contains the exact same characters with the exact same frequencies, reordered.
- Length Pre-Check: If
s.length !== t.length, they cannot be anagrams. Returnfalseimmediately. - Frequency Map: Traverse string
sand record character counts in a Hash Map (or a fixed 26-element array for lowercase English letters). - Frequency Verification: Traverse string
t. For each character, check if it exists in the map with a count $> 0$. Decrement its count in the map. If a character is missing or its count reaches negative, returnfalse. - Completion: If all characters in
tmatch and exhaust the counts ins, returntrue.
Why This Approach Works Best
Sorting both strings takes $O(n \log n)$ time. Using a frequency map checks anagrams in $O(n)$ time complexity and $O(k)$ space (where $k$ is the alphabet size, $O(1)$ for fixed character sets).
Example Walkthrough 1
s = "listen", t = "silent"
Same letters, different order.
s map: {l:1, i:1, s:1, t:1, e:1, n:1} -> t matches every key count exactly.
Frequency counts balance out to zero.
true
Valid anagram pair.
Answer: Anagram verification using frequency map
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (const ch of s) count[ch] = (count[ch] || 0) + 1;
for (const ch of t) {
if (!count[ch]) return false;
count[ch]--;
}
return true;
}Count character occurrences in the first string and verify them against the second string.
Always check string lengths first for instant early termination.
Frequency map eliminates the need for $O(n \log n)$ sorting operations.
For lowercase ASCII strings, a fixed 26-element array can replace a dynamic hash table for better performance.
06. First Non-Repeating Character in a String
Find the first non-repeating character in a string and return its index. If it does not exist, return -1.
How It Works & Algorithmic Design
This requires a Two-Pass Algorithm using a Frequency Map:
- First Pass (Counting): Iterate through the string from index $0$ to $n-1$ and build a frequency dictionary mapping each character to its occurrence count.
- Second Pass (Position Lookup): Iterate through the string a second time from left to right. Look up each character's count in the frequency map. The first character with a count equal to
1is our answer; return its current loop index. - Fallback: If all characters have counts $> 1$, return
-1.
Why This Approach Works Best
Checking every character against the rest of the string using nested loops takes $O(n^2)$ time. The two-pass Hash Map pattern reduces the time complexity to optimal linear $O(n)$ while taking $O(1)$ space for fixed alphabets.
Example Walkthrough
"leetcode"
Target string.
{ l:1, e:3, t:1, c:1, o:1, d:1 }
Frequency table built.
Index 0 = 'l', count is 1 -> Found!
Returns index 0.
0
First unique character is 'l' at index 0.
Answer: First unique character search
function firstUniqChar(s) {
const count = {};
for (const ch of s) count[ch] = (count[ch] || 0) + 1;
for (let i = 0; i < s.length; i++) {
if (count[s[i]] === 1) return i;
}
return -1;
}Build frequency counts first, then locate the first character with a count of 1.
Two-pass linear scans preserve original order while accumulating global frequencies.
Time complexity is $O(2n) = O(n)$.
Space complexity remains $O(1)$ when bounded by character set limits (e.g., ASCII/English letters).
07. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
How It Works & Algorithmic Design
This is solved using the Hash Map Complement Pattern:
- Mathematical Relation: For any element $x = \text{nums}[i]$, its required complementary pair is $y = \text{target} - x$.
- Hash Map Storage: Maintain a Hash Map where key =
array element valueand value =array index. - Single Pass: Loop through
numsusing index $i$:- Compute
complement = target - nums[i]. - Check if
complementexists in the Hash Map. - If it exists, return
[hashMap.get(complement), i]. - If not, insert
hashMap.put(nums[i], i)and continue.
- Compute
Why This Approach Works Best
Brute force nested loops take $O(n^2)$ time. Sorting followed by two pointers takes $O(n \log n)$ time and loses original indices. Hash Map lookup gives optimal $O(n)$ runtime and $O(n)$ space complexity.
Example Walkthrough
nums = [2, 7, 11, 15], target = 9
Target sum is 9.
Complement = 9 - 2 = 7. Map is empty -> Store {2: 0}
No complement yet.
Complement = 9 - 7 = 2. Found 2 in map at index 0!
Match found.
[0, 1]
Indices of values 2 and 7.
Answer: Two Sum using complement Hash Map
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
}Look up the target complement in a Hash Map during a single pass traversal.
Store visited elements in a map to turn $O(n^2)$ pair searches into $O(1)$ lookups.
Calculating
complement = target - currentavoids nested loops.Optimal single-pass runtime of $O(n)$ time and $O(n)$ space.
08. Find the Missing Number in an Array
Given an array nums containing $n$ distinct numbers in the range $[0, n]$, return the only number in the range that is missing from the array.
How It Works & Algorithmic Design
This problem can be solved mathematically using Gauss's Summation Formula or bit manipulation with XOR:
- Mathematical Sum Method:
- The sum of integers from $0$ to $n$ is calculated using the formula $S_n = \frac{n \cdot (n + 1)}{2}$.
- Calculate the actual sum of elements in
nums. - The missing number is simply $S_n - \text{actualSum}$.
- Bit Manipulation (XOR Method):
- XORing a number with itself yields zero ($a \oplus a = 0$).
- XOR all indices from $0$ to $n$ together with all values in
nums. Duplicate numbers cancel out, leaving only the missing number.
Why This Approach Works Best
Both methods run in $O(n)$ time complexity and $O(1)$ space without requiring array sorting ($O(n \log n)$) or extra hash sets ($O(n)$ space).
Example Walkthrough
[3, 0, 1] (n = 3)
Expected range [0, 1, 2, 3].
(3 * 4) / 2 = 6
Sum of numbers from 0 to 3.
3 + 0 + 1 = 4
Sum of given input array.
6 - 4 = 2
The missing number is 2.
Answer: Find missing number using Gauss's Sum
function missingNumber(nums) {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((acc, val) => acc + val, 0);
return expectedSum - actualSum;
}Subtract the array sum from the expected arithmetic progression total.
Gauss's summation formula $n(n+1)/2$ finds expected totals in $O(1)$ arithmetic steps.
XOR method prevents potential integer overflow in languages with fixed integer limits.
Both strategies achieve optimal $O(n)$ time and $O(1)$ space.
09. Move Zeroes to the End of Array
Given an integer array nums, move all 0s to the end of it while maintaining the relative order of the non-zero elements in-place.
How It Works & Algorithmic Design
This uses a Two-Pointer Write Boundary approach:
- Pointer Definition: Maintain a
insertPospointer initialized to index0. - Pass 1 (Shift Non-Zeroes): Iterate through the array with pointer $i$. Whenever
nums[i] !== 0, placenums[insertPos] = nums[i]and incrementinsertPos++. - Pass 2 (Fill Zeroes): Once all non-zero elements are moved to the front, loop from
insertPosto the end of the array and setnums[i] = 0.
Why This Approach Works Best
This solves the problem in-place without creating a duplicate array ($O(1)$ space). It executes in linear $O(n)$ time complexity.
Example Walkthrough
[0, 1, 0, 3, 12]
Array with scattered zeroes.
[1, 3, 12, 3, 12] (insertPos = 3)
Non-zero values shifted to indices 0, 1, 2.
[1, 3, 12, 0, 0]
Indices 3 to 4 filled with zeroes.
[1, 3, 12, 0, 0]
Zeroes pushed to end in-place.
Answer: Move zeroes in-place
function moveZeroes(nums) {
let insertPos = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[insertPos++] = nums[i];
}
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
return nums;
}Shift non-zero items to the front, then backfill remaining indices with zeroes.
Maintains relative order of non-zero elements by sequentially writing to
insertPos.Modifies original array reference directly ($O(1)$ space).
Linear time complexity $O(n)$ with two sequential simple loops.
10. Find Intersection of Two Arrays
Given two integer arrays nums1 and nums2, return an array of their unique intersection elements.
How It Works & Algorithmic Design
This problem uses Hash Set Intersection Filtering:
- Set Population: Convert
nums1into a Hash Setset1. Hash Sets store only unique elements and provide $O(1)$ membership checks. - Filtering: Initialize a second empty result set
resultSet. - Intersection Pass: Iterate through elements in
nums2. For every number $x$, ifset1.has(x), insert $x$ intoresultSet. - Return: Convert
resultSetback into an array list.
Why This Approach Works Best
Checking every element of nums2 against nums1 using nested loops takes $O(n \times m)$ time. Using a Hash Set reduces total execution time to linear $O(n + m)$ where $n$ and $m$ are the lengths of the two arrays.
Example Walkthrough
nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Arrays with duplicate entries.
{ 1, 2 }
Unique values from nums1.
2 in Set 1? Yes -> Add 2 to result.
Result set ensures uniqueness.
[2]
Unique common elements.
Answer: Array intersection using Hash Sets
function intersection(nums1, nums2) {
const set1 = new Set(nums1);
const result = new Set();
for (const num of nums2) {
if (set1.has(num)) result.add(num);
}
return Array.from(result);
}Use Hash Sets to find common elements in linear time.
Hash Sets eliminate duplicate results automatically.
Linear time performance $O(n + m)$ using $O(1)$ set membership checks.
Space complexity is proportional to unique elements stored in memory ($O(n)$).
11. Count the Number of Words in a String
Given a string containing words separated by spaces, count the number of words.
How It Works & Algorithmic Design
A simple approach is to split the string into words after trimming surrounding whitespace:
- Remove leading and trailing whitespace.
- If the resulting string is empty, return
0. - Split the string using whitespace as the delimiter.
- Return the number of resulting words.
Why This Approach Works Best
For an easy-level problem, splitting provides a clear and readable solution. The time complexity is $O(n)$ where $n$ is the string length. The resulting word collection requires $O(n)$ space.
Example Walkthrough
"I love programming"
The sentence contains three words.
["I", "love", "programming"]
Whitespace separates the words.
3
There are three words.
Answer: Count words
function countWords(str) {
const trimmed = str.trim();
if (trimmed === '') return 0;
return trimmed.split(/\s+/).length;
}Trim the input and split it using whitespace.
Whitespace should be handled carefully when counting words.
Trimming and splitting makes the basic solution easy to understand.
The operation takes O(n) time.
12. Count Digits in a Number
Given an integer, count how many digits it contains.
How It Works & Algorithmic Design
For a positive integer, repeatedly divide the number by 10:
- Handle
0as a special case because it contains one digit. - Convert negative values to their absolute value.
- Repeatedly divide by
10using integer division. - Increment the digit counter after every division.
- Stop when the number becomes
0.
Why This Approach Works Best
Each iteration removes one decimal digit. Therefore the time complexity is $O(d)$ where $d$ is the number of digits, with $O(1)$ space.
Example Walkthrough
5832
The number contains four digits.
5832 -> 583 -> 58 -> 5 -> 0
Each division by 10 removes the last digit.
4
Four divisions were required.
Answer: Count digits
function countDigits(n) {
n = Math.abs(n);
if (n === 0) return 1;
let count = 0;
while (n > 0) {
n = Math.floor(n / 10);
count++;
}
return count;
}Repeatedly remove the last digit using division by 10.
Integer division by 10 removes the last decimal digit.
Zero must be handled separately because 0 contains one digit.
The algorithm uses constant auxiliary space.
13. Find the Sum of Digits of a Number
Given an integer, calculate the sum of all its digits.
How It Works & Algorithmic Design
Use modulo and integer division:
- Convert the number to its absolute value.
- Extract the last digit using
n % 10. - Add the digit to
sum. - Remove the last digit using integer division by
10. - Continue until the number becomes
0.
Why This Approach Works Best
Each digit is processed exactly once, resulting in $O(d)$ time where $d$ is the number of digits and $O(1)$ space.
Example Walkthrough
583
The number contains digits 5, 8, and 3.
3 + 8 + 5 = 16
Digits are extracted from right to left.
16
The sum of all digits is 16.
Answer: Sum digits
function sumDigits(n) {
n = Math.abs(n);
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
}Extract each digit using modulo 10 and remove it using integer division.
The modulo operator extracts the last digit.
Integer division removes the processed digit.
Each digit is visited once, giving O(d) time.
14. Reverse the Digits of a Number
Given an integer, reverse the order of its digits.
How It Works & Algorithmic Design
Build the reversed number from right to left:
- Extract the last digit using
% 10. - Shift the current result left by one decimal position using
result * 10. - Add the extracted digit.
- Remove the last digit from the original number using integer division by
10. - Continue until the original number becomes
0.
Why This Approach Works Best
The algorithm processes each digit exactly once, requiring $O(d)$ time and $O(1)$ auxiliary space.
Example Walkthrough
1234
The digits need to be reversed.
4 -> 43 -> 432 -> 4321
Each extracted digit is appended to the reversed number.
4321
The digits appear in reverse order.
Answer: Reverse a number
function reverseNumber(n) {
const sign = n < 0 ? -1 : 1;
n = Math.abs(n);
let result = 0;
while (n > 0) {
const digit = n % 10;
result = result * 10 + digit;
n = Math.floor(n / 10);
}
return sign * result;
}Extract digits from right to left and append them to a new number.
Modulo extracts the final digit.
Multiplying the result by 10 shifts existing digits left.
The solution processes every digit once.
15. Check Whether a Number Is a Palindrome
Determine whether a number reads the same from left to right and right to left.
How It Works & Algorithmic Design
A number is a palindrome if it equals its reversed form:
- Store the original number.
- Reverse the number using digit extraction.
- Compare the reversed number with the original.
- Return
truewhen they are equal; otherwise returnfalse.
Why This Approach Works Best
The number is processed digit by digit. The algorithm requires $O(d)$ time and $O(1)$ auxiliary space.
Example Walkthrough
1221
The digits are symmetric.
1221
Reversing the number produces the same value.
true
Original and reversed values are equal.
Answer: Check numeric palindrome
function isPalindrome(n) {
if (n < 0) return false;
const original = n;
let reversed = 0;
while (n > 0) {
reversed = reversed * 10 + (n % 10);
n = Math.floor(n / 10);
}
return original === reversed;
}Reverse the number and compare it with the original value.
A numeric palindrome is equal to its reversed value.
Negative numbers are generally not considered numeric palindromes.
The solution takes O(d) time and O(1) space.
16. Count the Occurrences of a Character
Given a string and a target character, count how many times the character appears.
How It Works & Algorithmic Design
Use a simple counting traversal:
- Initialize
count = 0. - Visit every character in the string.
- Compare it with the target character.
- Increment the counter when they match.
- Return the final count.
Why This Approach Works Best
Every character may contribute to the result, so the entire string must be inspected. The algorithm uses $O(n)$ time and $O(1)$ additional space.
Example Walkthrough
String="banana", Target="a"
The character a appears multiple times.
b -> a(count=1) -> n -> a(count=2) -> n -> a(count=3)
The counter increments only for matching characters.
3
The character a appears three times.
Answer: Count a character
function countCharacter(str, target) {
let count = 0;
for (const char of str) {
if (char === target) count++;
}
return count;
}Traverse every character and increment the counter whenever it matches the target.
Character counting is a direct application of the accumulator pattern.
Every character must be checked.
The algorithm uses O(n) time and O(1) extra space.
17. Remove Spaces from a String
Given a string, create a new string with all space characters removed.
How It Works & Algorithmic Design
Traverse the string and keep only non-space characters:
- Create an empty result string.
- Visit each character.
- If the character is not a space, append it to the result.
- Return the resulting string.
Why This Approach Works Best
Every character must be examined, giving $O(n)$ time. A new string is produced, requiring $O(n)$ output space.
Example Walkthrough
"hello world from JS"
The string contains spaces between words.
"hello" + "world" + "from" + "JS"
Space characters are skipped.
"helloworldfromJS"
All spaces have been removed.
Answer: Remove spaces
function removeSpaces(str) {
let result = '';
for (const char of str) {
if (char !== ' ') result += char;
}
return result;
}Build a new string containing only non-space characters.
This is a filtering problem over characters.
Characters that do not satisfy the condition are skipped.
A new string requires additional output space.
18. Convert Lowercase Characters to Uppercase
Given a string, convert its lowercase alphabetic characters to uppercase.
How It Works & Algorithmic Design
Traverse each character and transform lowercase letters:
- Visit each character.
- Check whether it is lowercase.
- Convert it to uppercase when necessary.
- Preserve non-letter characters.
- Build and return the transformed string.
Why This Approach Works Best
Every character must be inspected, so the time complexity is $O(n)$. The result requires $O(n)$ output space.
Example Walkthrough
"hello World 123"
The string contains lowercase, uppercase, and non-letter characters.
"hello World 123" -> "HELLO WORLD 123"
Lowercase letters are converted while other characters remain unchanged.
"HELLO WORLD 123"
All alphabetic characters are uppercase.
Answer: Convert string to uppercase
function toUpperCase(str) {
let result = '';
for (const char of str) {
result += char.toUpperCase();
}
return result;
}Transform each character using the language's standard uppercase conversion.
String transformation can be performed one character at a time.
Non-letter characters remain unchanged.
The transformation requires O(n) time.
19. Find the First Repeated Character
Given a string, find the first character that appears more than once.
How It Works & Algorithmic Design
Use a set to remember characters already encountered:
- Create an empty set.
- Traverse the string from left to right.
- If the current character already exists in the set, return it immediately.
- Otherwise, add it to the set.
- If no character repeats, return
nullor an equivalent empty value.
Why This Approach Works Best
A set provides efficient membership checking. The expected time complexity is $O(n)$ and the additional space complexity is $O(n)$.
Example Walkthrough
"programming"
Characters are inspected from left to right.
p -> r -> o -> g -> r (already seen)
The second occurrence of r is the first repeated character.
"r"
r is the first character encountered for the second time.
Answer: Find first repeated character
function firstRepeated(str) {
const seen = new Set();
for (const char of str) {
if (seen.has(char)) return char;
seen.add(char);
}
return null;
}Use a hash set to remember characters that have already appeared.
A hash set provides efficient membership checking.
Returning immediately ensures the first repeated character is found.
Expected time is O(n) with O(n) additional space.
20. Check Whether a Number Is Prime
Determine whether a given integer is a prime number.
How It Works & Algorithmic Design
A prime number greater than 1 has exactly two positive divisors: 1 and itself.
- Numbers less than
2are not prime. - Try dividing the number by integers starting from
2. - Only test divisors up to the square root of the number.
- If any divisor divides evenly, the number is not prime.
- Otherwise, it is prime.
Why This Approach Works Best
If a number has a factor larger than its square root, the corresponding paired factor must be smaller than the square root. Therefore checking up to sqrt(n) is sufficient. The time complexity is $O(\sqrt n)$ and space is $O(1)$.
Example Walkthrough
29
29 is greater than 1 and needs to be tested for divisors.
29 % 2 != 0 | 29 % 3 != 0 | 29 % 4 != 0 | 29 % 5 != 0
Testing only up to sqrt(29), approximately 5.38, is sufficient.
true
No divisor was found, so 29 is prime.
Answer: Check for prime number
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}Test possible divisors only up to the square root of the number.
Numbers below 2 are not prime.
Checking divisors only up to the square root is sufficient.
The optimized trial-division approach runs in O(√n) time and O(1) space.