0% found this document useful (0 votes)
2 views67 pages

Problem Solving With Solution

The document outlines a series of programming problems and their solutions, focusing on array and string manipulations, as well as object-based challenges. Each problem includes a description, input examples, expected output, and edge cases to consider. The problems cover a wide range of topics, including frequency counting, array rotation, string reversal, and object key manipulation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views67 pages

Problem Solving With Solution

The document outlines a series of programming problems and their solutions, focusing on array and string manipulations, as well as object-based challenges. Each problem includes a description, input examples, expected output, and edge cases to consider. The problems cover a wide range of topics, including frequency counting, array rotation, string reversal, and object key manipulation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Remove All Non-Duplicate Values from an Array


● Problem: Given an array of strings, return only the elements that appear more than
once.
● Input: ["apple", "banana", "apple", "orange"]
● Output: ["apple", "apple"]
● Edge Cases:
○ Empty array => return []
○ All elements unique => return []

2. First Non-Repeating Element


● Problem: Return the first element in the array that appears only once.
● Input: ["a", "b", "c", "a", "b", "d"]
● Output: "c"
● Edge Cases:
○ All repeating => return null or a message
○ Empty array => return null

3. Element(s) with Highest Frequency


● Problem: Return the element(s) with the highest count in the array.
● Input: ["a", "b", "a", "c", "b", "a"]
● Output: ["a"]
● Edge Cases:
○ Tie in frequency => return all tied values

4. Group Elements by Index


● Problem: Return a map where each element maps to a list of its indices.
● Input: ["a", "b", "a", "c", "b", "a"]
● Output: { a: [0,2,5], b: [1,4], c: [3] }
● Edge Cases:
○ Empty array => return {}

5. Rotate Array Without Extra Space

● Problem: Rotate the array to the right by k positions.


● Input: [1, 2, 3, 4, 5], k = 2
● Output: [4, 5, 1, 2, 3]
● Edge Cases:
○ k > [Link]
○ Negative or zero k => no rotation

6. Flatten Nested Arrays


● Problem: Convert a nested array of any depth to a flat array.
● Input: [1, [2, [3, [4]], 5]]
● Output: [1, 2, 3, 4, 5]
● Edge Cases:
○ Array with no nesting => return as is
○ Empty array or nested empty arrays

7. Count Frequency Without reduce()


● Problem: Return a map of frequency of each element.
● Input: ["apple", "banana", "apple"]
● Output: { apple: 2, banana: 1 }
● Edge Cases:
○ All unique => frequency 1 each

8. Find All Pairs with Given Sum


● Problem: Return all unique pairs that add to a target sum.
● Input: [1, 2, 3, 4, 5], sum = 6
● Output: [[1, 5], [2, 4]]
● Edge Cases:
○ No valid pairs => return []

9. Unique Triplets That Sum to 0


● Problem: Return all unique triplets that sum to 0.
● Input: [-1, 0, 1, 2, -1, -4]
● Output: [[-1, -1, 2], [-1, 0, 1]]
● Edge Cases:
○ Less than 3 elements => return []
10. Are Two Arrays Anagrams?
● Problem: Check if two arrays have the same elements, in any order.
● Input: ["a", "b", "c"], ["c", "a", "b"]
● Output: true
● Edge Cases:
○ Different lengths => false
○ Repeated elements => match by frequency

11. Strings Starting with a Vowel


● Problem: Return all strings that start with a vowel.
● Input: ["apple", "banana", "orange"]
● Output: ["apple", "orange"]
● Edge Cases:
○ Empty array => []
○ Upper/lowercase handling

12. Rearrange by String Length


● Problem: Sort strings by their length.
● Input: ["a", "abc", "ab"]
● Output: ["a", "ab", "abc"]
● Edge Cases:
○ Strings of same length

13. Palindromes Only


● Problem: Return only palindrome strings from array.
● Input: ["madam", "car", "level"]
● Output: ["madam", "level"]
● Edge Cases:
○ Empty array
○ Case sensitivity

14. Common Elements in Multiple Arrays


● Problem: Return elements common to all arrays.
● Input: [[1,2,3],[2,3,4],[2,5,3]]
● Output: [2,3]
● Edge Cases:
○ Any empty subarray => return []

15. Group by First Letter


● Problem: Return an object with keys as first letters.
● Input: ["apple", "bat", "ball"]
● Output: { a: ["apple"], b: ["bat", "ball"] }
● Edge Cases:
○ Mixed cases like "Apple" and "apple"

16. Longest Consecutive Sequence


● Problem: Return the longest consecutive integer sequence.
● Input: [100, 4, 200, 1, 3, 2]
● Output: [1,2,3,4]
● Edge Cases:
○ Duplicate values
○ Unsorted input

17. Subarray with Given Sum


● Problem: Return a subarray that sums to target value.
● Input: [1, 2, 3, 7, 5], sum = 12
● Output: [2, 3, 7]
● Edge Cases:
○ No subarray found => []

18. Index of Element Without indexOf()

● Problem: Return index of given element without using indexOf().


● Input: ["a", "b", "c"], find: "b"
● Output: 1
● Edge Cases:
○ Element not found => -1

19. Replace All Occurrences


● Problem: Replace all occurrences of a value.
● Input: ["apple", "banana", "apple"], replace "apple" with "kiwi"
● Output: ["kiwi", "banana", "kiwi"]
● Edge Cases:
○ No match found => unchanged array

20. Merge Two Arrays Alternately


● Problem: Interleave two arrays element-by-element.
● Input: [1, 2, 3], ["a", "b", "c"]
● Output: [1, "a", 2, "b", 3, "c"]
● Edge Cases:
○ Unequal lengths => append remaining elements

String

1. Reverse Words in a Sentence


● Problem: Reverse the order of words in a sentence.
● Input: "I love coding"
● Output: "coding love I"
● Edge Cases:
○ Extra spaces between words
○ Leading/trailing spaces

2. Remove All Duplicate Characters


● Problem: Return a string with only unique characters (first occurrence only).
● Input: "programming"
● Output: "progamin"
● Edge Cases:
○ Case sensitivity
3. Find First Non-Repeating Character
● Problem: Return the first character that appears only once.
● Input: "aabbcdeff"
● Output: "c"
● Edge Cases:
○ All characters repeating => return null

4. Check for Anagram (Ignoring Case & Spaces)


● Problem: Check if two strings are anagrams, ignoring spaces and case.
● Input: "Dormitory", "Dirty room"
● Output: true
● Edge Cases:
○ Punctuation, case, whitespace differences

5. Count Vowels and Consonants


● Problem: Return a count of vowels and consonants in a string.
● Input: "Hello World"
● Output: { vowels: 3, consonants: 7 }
● Edge Cases:
○ Ignore non-alphabetic characters

6. Longest Word in a Sentence


● Problem: Return the longest word.
● Input: "The quick brown fox"
● Output: "quick"
● Edge Cases:
○ Multiple longest words => return first

7. Capitalize First Letter of Each Word


● Problem: Convert each word to start with uppercase.
● Input: "hello world"
● Output: "Hello World"
● Edge Cases:
○ Extra/multiple spaces
8. Check If String is Palindrome (Ignore Non-Alpha)
● Problem: Check if string is a palindrome, ignoring non-alphabetic characters.
● Input: "A man, a plan, a canal: Panama"
● Output: true
● Edge Cases:
○ Punctuation and case ignored

9. Compress Consecutive Characters


● Problem: Return run-length encoding.
● Input: "aaabbc"
● Output: "a3b2c1"
● Edge Cases:
○ Empty string => ""

10. Find All Substrings of a Given String


● Problem: Return a list of all possible substrings.
● Input: "abc"
● Output: ["a", "ab", "abc", "b", "bc", "c"]
● Edge Cases:
○ Empty input => []

11. Count Occurrences of a Word


● Problem: Count how many times a word appears in a sentence.
● Input: "the dog chased the cat", word = "the"
● Output: 2
● Edge Cases:
○ Case insensitive match

12. Replace All Digits with Dashes


● Problem: Replace all digits in a string with "-".
● Input: "abc123def"
● Output: "abc---def"
● Edge Cases:
○ No digits => unchanged
13. Remove Characters Present in Another String
● Problem: Remove from first string all chars that appear in second string.
● Input: str1 = "battle", str2 = "belt"
● Output: "a"
● Edge Cases:
○ Case sensitivity

14. Toggle Case of Each Letter


● Problem: Change uppercase to lowercase and vice versa.
● Input: "HeLLo"
● Output: "hEllO"
● Edge Cases:
○ Non-alphabetic characters remain unchanged

15. Most Frequent Character


● Problem: Return the character with the highest frequency.
● Input: "mississippi"
● Output: "i"
● Edge Cases:
○ Tie => return first max

16. Remove All White Spaces


● Problem: Return string without any white spaces.
● Input: " a b c d "
● Output: "abcd"
● Edge Cases:
○ Tabs/newlines count as whitespace too

17. Find All Duplicates


● Problem: Return all characters that appear more than once.
● Input: "aabbcde"
● Output: ["a", "b"]
● Edge Cases:
○ Case sensitivity
18. Find Common Characters Between Two Strings
● Problem: Return a list of characters found in both strings.
● Input: "abcdef", "bdfhij"
● Output: ["b", "d", "f"]
● Edge Cases:
○ Repeats counted once

19. Remove Duplicate Words from Sentence


● Problem: Return sentence with only the first occurrence of each word.
● Input: "this is is a test test"
● Output: "this is a test"
● Edge Cases:
○ Case sensitivity ("This" vs "this")

20. Shift Characters by N (Caesar Cipher Basic)


● Problem: Shift each letter forward by N positions.
● Input: "abc", n = 2
● Output: "cde"
● Edge Cases:
○ Wrap around from z to a
Object-Based Problems (20)

All problems involve JavaScript objects (as data structures).

1. Filter Object Keys by Value Type


○ Statement: Return only keys whose values are of a specified type (e.g.,
'string').
○ Input: { name: "Alice", age: 30, isStudent: false }, type:
'string'
○ Output: ['name']
○ Edge Case: Empty object, no matching type, nested objects.
2. Merge Two Objects Without Overwriting
○ Statement: Merge properties of two objects, keeping original values if keys
conflict.
○ Input: {a: 1, b: 2}, {b: 3, c: 4}
○ Output: {a: 1, b: 2, c: 4}
○ Edge Case: One empty object, all keys conflict.
3. Invert an Object
○ Statement: Swap the keys and values of an object.
○ Input: { a: "1", b: "2" }
○ Output: { "1": "a", "2": "b" }
○ Edge Case: Non-primitive values, duplicate values.
4. Group Objects by a Property
○ Statement: Group an array of objects by a given key.
○ Input: [{type: 'fruit', name: 'apple'}, {type: 'veg', name:
'carrot'}]
○ Output: { fruit: [{...}], veg: [{...}] }
○ Edge Case: Missing keys, null values.
5. Convert Object to Array of Key-Value Pairs
○ Statement: Convert an object into an array like [[key, value]].
○ Input: {a: 1, b: 2}
○ Output: [["a", 1], ["b", 2]]
○ Edge Case: Nested object, empty object.
6. Compare Two Objects for Deep Equality
○ Statement: Check if two objects are deeply equal.
○ Input: {a: {b: 2}}, {a: {b: 2}}
○ Output: true
○ Edge Case: Nested objects, undefined values.
7. Find Duplicate Values Across Objects in Array
○ Statement: Return keys that have duplicate values across object entries.
○ Input: [{a: 1, b: 2}, {a: 2, b: 2}]
○ Output: ["b"]
○ Edge Case: No duplicates, different keys.
8. Remove Keys with Null or Undefined Values
○ Statement: Clean an object by removing null/undefined values.
○ Input: {a: null, b: 2, c: undefined}
○ Output: {b: 2}
○ Edge Case: All values are null/undefined, nested keys.
9. Count Frequency of Each Value in Object Array
○ Statement: Count how often each value appears in a key across array of
objects.
○ Input: [{type: 'a'}, {type: 'b'}, {type: 'a'}]
○ Output: { a: 2, b: 1 }
○ Edge Case: Empty array, missing key.
10. Rename Keys in an Object Based on Map
● Statement: Use a key mapping to rename object keys.
● Input: {fname: 'John', lname: 'Doe'}, map: {fname: 'firstName',
lname: 'lastName'}
● Output: {firstName: 'John', lastName: 'Doe'}
● Edge Case: Missing mapping, partial mapping.
11. Find Intersection of Object Keys
● Statement: Return array of keys common in both objects.
● Input: {a:1, b:2}, {b:3, c:4}
● Output: ["b"]
● Edge Case: No common keys, empty object.
12. Sort Object by Value (Ascending)
● Statement: Return entries of object sorted by value.
● Input: {a: 3, b: 1, c: 2}
● Output: [["b",1],["c",2],["a",3]]
● Edge Case: Duplicate values, string values.
13. Convert Query String to Object
● Statement: Turn a URL query string into an object.
● Input: 'name=John&age=30'
● Output: {name: 'John', age: '30'}
● Edge Case: Empty string, repeated keys.
14. Validate Required Object Keys
● Statement: Ensure object has all required keys.
● Input: {a: 1, b: 2}, required: ["a", "b", "c"]
● Output: false
● Edge Case: Case sensitivity, null values.
15. Find Keys with Numeric Values Only
● Statement: Return keys with values of type number.
● Input: {a: 1, b: "text", c: 3}
● Output: ["a", "c"]
● Edge Case: NaN, nested numbers.
16. Group Object Keys by Value Type
● Statement: Group keys of object by value type.
● Input: {a: 1, b: "text", c: true}
● Output: { number: ["a"], string: ["b"], boolean: ["c"] }
● Edge Case: Undefined/null values.
17. Serialize Nested Object into Dot Notation
● Statement: Flatten nested object using dot-separated keys.
● Input: {a: {b: 2}}
● Output: {"a.b": 2}
● Edge Case: Multiple levels, empty objects.
18. Clone Object Deeply
● Statement: Create a deep copy of an object.
● Input: {a: {b: 2}}
● Output: A new object deeply equal but not the same reference.
● Edge Case: Circular references, undefined values.
19. Replace Values in Object by Rule
● Statement: Replace all string values to uppercase.
● Input: {a: "apple", b: 2}
● Output: {a: "APPLE", b: 2}
● Edge Case: Mixed types, null values.
20. Sum All Numeric Values in Object
● Statement: Add all number values in an object.
● Input: {a: 5, b: "4", c: 1}
● Output: 6
● Edge Case: Strings that look like numbers, nested numbers.

✅ 1. Most Frequent Array Item


Input: [1, 3, 2, 1, 4, 1, 3] → Output: 1

Brute Force
js
CopyEdit
function mostFrequentBrute(arr) {
let maxCount = 0, mostFrequent = arr[0];
for (let i = 0; i < [Link]; i++) {
let count = 0;
for (let j = 0; j < [Link]; j++) {
if (arr[i] === arr[j]) count++;
}
if (count > maxCount) {
maxCount = count;
mostFrequent = arr[i];
}
}
return mostFrequent;
}

Optimized using Map


js
CopyEdit
function mostFrequentMap(arr) {
const freq = new Map();
let max = 0, res;
for (let num of arr) {
[Link](num, ([Link](num) || 0) + 1);
if ([Link](num) > max) {
max = [Link](num);
res = num;
}
}
return res;
}

Optimal using Object


js
CopyEdit
function mostFrequentObject(arr) {
const count = {};
let max = 0, res;
for (let el of arr) {
count[el] = (count[el] || 0) + 1;
if (count[el] > max) {
max = count[el];
res = el;
}
}
return res;
}

✅ 2. Swap Case in String


Input: "HeLLo" → Output: "hEllO"

Brute Force
js
CopyEdit
function swapCase(str) {
let res = '';
for (let ch of str) {
res += ch === [Link]() ? [Link]() :
[Link]();
}
return res;
}

Optimized using Array map


js
CopyEdit
function swapCaseOptimized(str) {
return [...str].map(ch =>
ch === [Link]() ? [Link]() : [Link]()
).join('');
}

Optimal using regex


js
CopyEdit
function swapCaseRegex(str) {
return [Link](/([a-z])|([A-Z])/g, (_, lower, upper) =>
lower ? [Link]() : [Link]()
);
}

✅ 3. Print Nested Array Elements


Input: [1, [2, [3, 4]], 5] → Output: 1 2 3 4 5
Brute Force (manual recursion)
js
CopyEdit
function printNested(arr) {
for (let el of arr) {
if ([Link](el)) printNested(el);
else [Link](el);
}
}

Optimized (flatten and print)


js
CopyEdit
function printNestedFlat(arr) {
const flat = [Link](Infinity);
[Link]([Link]);
}

Optimal (use generator)


js
CopyEdit
function* flatten(arr) {
for (let el of arr) {
if ([Link](el)) yield* flatten(el);
else yield el;
}
}
[...flatten([1, [2, [3, 4]], 5])].forEach([Link]);

✅ 4. Sum and Product of Array


Input: [1, 2, 3, 4] → Output: Sum = 10, Product = 24

Brute Force
js
CopyEdit
function sumProductBrute(arr) {
let sum = 0, product = 1;
for (let i = 0; i < [Link]; i++) {
sum += arr[i];
product *= arr[i];
}
return { sum, product };
}

Optimized using for...of


js
CopyEdit
function sumProductOptimized(arr) {
let sum = 0, product = 1;
for (let num of arr) {
sum += num;
product *= num;
}
return { sum, product };
}

Optimal using reduce


js
CopyEdit
function sumProductOptimal(arr) {
return [Link]((acc, val) => {
[Link] += val;
[Link] *= val;
return acc;
}, { sum: 0, product: 1 });
}

✅ 5. Shuffle Array
Brute Force (Not perfect randomness)
js
CopyEdit
function shuffleBrute(arr) {
return [Link](() => [Link]() - 0.5);
}

Optimized (Fisher-Yates Shuffle)


js
CopyEdit
function shuffleOptimized(arr) {
let a = [...arr];
for (let i = [Link] - 1; i > 0; i--) {
let j = [Link]([Link]() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}

Optimal (In-place shuffle)


js
CopyEdit
function shuffleOptimal(arr) {
for (let i = [Link] - 1; i > 0; i--) {
let j = [Link]([Link]() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}

✅ 6. Binary Search
Requires sorted array.

Brute Force (Linear Search)


js
CopyEdit
function binarySearchBrute(arr, target) {
for (let i = 0; i < [Link]; i++) {
if (arr[i] === target) return i;
}
return -1;
}

Optimized (Binary Search Iterative)


js
CopyEdit
function binarySearchOptimized(arr, target) {
let left = 0, right = [Link] - 1;
while (left <= right) {
let mid = [Link]((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}

Optimal (Recursive)
js
CopyEdit
function binarySearchRecursive(arr, target, left = 0, right =
[Link] - 1) {
if (left > right) return -1;
let mid = [Link]((left + right) / 2);
if (arr[mid] === target) return mid;
return arr[mid] < target
? binarySearchRecursive(arr, target, mid + 1, right)
: binarySearchRecursive(arr, target, left, mid - 1);
}

✅ 7. Sum of Arrays by Index


Input: [1,2,3] and [4,5] → Output: [5, 7, 3]

Brute Force
js
CopyEdit
function sumByIndexBrute(a, b) {
let result = [];
let len = [Link]([Link], [Link]);
for (let i = 0; i < len; i++) {
result[i] = (a[i] || 0) + (b[i] || 0);
}
return result;
}

Optimized using map


js
CopyEdit
function sumByIndexOptimized(a, b) {
return [Link]({ length: [Link]([Link], [Link]) },
(_, i) => (a[i] || 0) + (b[i] || 0));
}

Optimal using spread + map


js
CopyEdit
function sumByIndexOptimal(a, b) {
const len = [Link]([Link], [Link]);
return [...Array(len)].map((_, i) => (a[i] || 0) + (b[i] || 0));
}

✅ 8. Union of Two Arrays


Input: [1,2] and [2,3] → Output: [1,2,3]

Brute Force
js
CopyEdit
function unionBrute(a, b) {
let res = [...a];
for (let el of b) {
if (![Link](el)) [Link](el);
}
return res;
}

Optimized using Set


js
CopyEdit
function unionOptimized(a, b) {
return [Link](new Set([...a, ...b]));
}

Optimal using Set and spread


js
CopyEdit
const unionOptimal = (a, b) => [...new Set([...a, ...b])];

✅ 9. Find Pair with Target Sum


Input: [1,2,3,4], target = 5 → Output: [1,4] or [2,3]

Brute Force
js
CopyEdit
function findPairBrute(arr, target) {
for (let i = 0; i < [Link]; i++) {
for (let j = i + 1; j < [Link]; j++) {
if (arr[i] + arr[j] === target) return [arr[i], arr[j]];
}
}
return [];
}
Optimized using Map
js
CopyEdit
function findPairOptimized(arr, target) {
let map = new Map();
for (let num of arr) {
let diff = target - num;
if ([Link](diff)) return [diff, num];
[Link](num, true);
}
return [];
}

Optimal using Set


js
CopyEdit
function findPairOptimal(arr, target) {
const seen = new Set();
for (let num of arr) {
if ([Link](target - num)) return [target - num, num];
[Link](num);
}
return [];
}

✅ 10. Retrieve Property Values


Input: [{a:1}, {a:2}, {a:3}], key = 'a' → [1,2,3]

Brute Force
js
CopyEdit
function getPropsBrute(arr, key) {
let res = [];
for (let i = 0; i < [Link]; i++) {
[Link](arr[i][key]);
}
return res;
}

Optimized using for...of


js
CopyEdit
function getPropsOptimized(arr, key) {
let res = [];
for (let obj of arr) [Link](obj[key]);
return res;
}

Optimal using map


js
CopyEdit
const getPropsOptimal = (arr, key) => [Link](obj => obj[key]);

✅ 11. Longest Common Starting Substring


Input: ["flower", "flow", "flight"] → Output: "fl"

Brute Force
js
CopyEdit
function lcpBrute(arr) {
let prefix = arr[0] || "";
for (let i = 1; i < [Link]; i++) {
let temp = "";
for (let j = 0; j < [Link] && j < arr[i].length; j++) {
if (prefix[j] === arr[i][j]) temp += prefix[j];
else break;
}
prefix = temp;
}
return prefix;
}

Optimized using sort


js
CopyEdit
function lcpOptimized(arr) {
if (![Link]) return '';
[Link]();
let [first, last] = [arr[0], arr[[Link] - 1]];
let i = 0;
while (i < [Link] && first[i] === last[i]) i++;
return [Link](0, i);
}

Optimal using every


js
CopyEdit
function lcpOptimal(arr) {
if (![Link]) return '';
let prefix = '';
for (let i = 0; i < arr[0].length; i++) {
let char = arr[0][i];
if ([Link](word => word[i] === char)) {
prefix += char;
} else break;
}
return prefix;
}
1. Remove All Non-Duplicate Values from an Array
Brute Force:

javascript
function removeNonDuplicates(arr) {
const result = [];
for (let i = 0; i < [Link]; i++) {
if ([Link](arr[i]) !== [Link](arr[i])) {
[Link](arr[i]);
}
}
return result;
}
Better:

javascript
function removeNonDuplicates(arr) {
const frequency = {};
[Link](item => frequency[item] = (frequency[item] || 0) + 1);
return [Link](item => frequency[item] > 1);
}
Optimal:

javascript
function removeNonDuplicates(arr) {
const seen = new Set();
const duplicates = new Set();
[Link](item => [Link](item) ? [Link](item) : [Link](item));
return [Link](item => [Link](item));
}
2. First Non-Repeating Element
Brute Force:

javascript
function firstNonRepeating(arr) {
for (let i = 0; i < [Link]; i++) {
if ([Link](arr[i]) === [Link](arr[i])) {
return arr[i];
}
}
return null;
}
Better:

javascript
function firstNonRepeating(arr) {
const frequency = {};
[Link](item => frequency[item] = (frequency[item] || 0) + 1);
for (const item of arr) {
if (frequency[item] === 1) return item;
}
return null;
}
Optimal:

javascript
function firstNonRepeating(arr) {
const seen = new Map();
[Link]((item, index) => {
if ([Link](item)) [Link](item, -1);
else [Link](item, index);
});
for (const [key, value] of seen) {
if (value !== -1) return key;
}
return null;
}
3. Element(s) with Highest Frequency
Brute Force:

javascript
function highestFrequency(arr) {
const frequency = {};
let max = 0;
[Link](item => {
frequency[item] = (frequency[item] || 0) + 1;
max = [Link](max, frequency[item]);
});
return [Link](frequency).filter(key => frequency[key] === max);
}
Better:

javascript
function highestFrequency(arr) {
const frequency = new Map();
let max = 0;
[Link](item => {
const count = ([Link](item) || 0) + 1;
[Link](item, count);
max = [Link](max, count);
});
return [...frequency].filter(([key, val]) => val === max).map(([key]) => key);
}
Optimal:

javascript
function highestFrequency(arr) {
const frequency = {};
let max = 0;
let result = [];
[Link](item => {
frequency[item] = (frequency[item] || 0) + 1;
if (frequency[item] > max) {
max = frequency[item];
result = [item];
} else if (frequency[item] === max) {
[Link](item);
}
});
return result;
}
4. Group Elements by Index
Brute Force:

javascript
function groupByIndex(arr) {
const result = {};
for (let i = 0; i < [Link]; i++) {
if (!result[arr[i]]) result[arr[i]] = [];
result[arr[i]].push(i);
}
return result;
}
Better:

javascript
function groupByIndex(arr) {
return [Link]((acc, item, index) => {
acc[item] = (acc[item] || []).concat(index);
return acc;
}, {});
}
Optimal:

javascript
function groupByIndex(arr) {
const result = {};
[Link]((item, index) => {
result[item] ? result[item].push(index) : (result[item] = [index]);
});
return result;
}
5. Rotate Array Without Extra Space
Brute Force:

javascript
function rotateArray(arr, k) {
k = k % [Link];
for (let i = 0; i < k; i++) {
[Link]([Link]());
}
return arr;
}
Better:

javascript
function rotateArray(arr, k) {
k = k % [Link];
const rotated = [...[Link](-k), ...[Link](0, -k)];
return rotated;
}
Optimal:

javascript
function rotateArray(arr, k) {
k = k % [Link];
reverse(arr, 0, [Link] - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, [Link] - 1);
return arr;
}
function reverse(arr, start, end) {
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
}
6. Flatten Nested Arrays
Brute Force:

javascript
function flatten(arr) {
return [Link]().split(',').map(Number);
}
Better:

javascript
function flatten(arr) {
return [Link]((acc, val) =>
[Link](val) ? [Link](flatten(val)) : [Link](val), []);
}
Optimal:

javascript
function flatten(arr) {
const stack = [...arr];
const result = [];
while ([Link]) {
const next = [Link]();
if ([Link](next)) [Link](...next);
else [Link](next);
}
return result;
}
7. Count Frequency Without reduce()
Brute Force:

javascript
function countFrequency(arr) {
const frequency = {};
for (const item of arr) {
frequency[item] = (frequency[item] || 0) + 1;
}
return frequency;
}
Better:

javascript
function countFrequency(arr) {
const frequency = new Map();
[Link](item =>
[Link](item, ([Link](item) || 0) + 1);
return [Link](frequency);
}
Optimal:

javascript
function countFrequency(arr) {
return [Link]((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
}
8. Find All Pairs with Given Sum
Brute Force:

javascript
function findPairs(arr, sum) {
const pairs = [];
for (let i = 0; i < [Link]; i++) {
for (let j = i + 1; j < [Link]; j++) {
if (arr[i] + arr[j] === sum) [Link]([arr[i], arr[j]]);
}
}
return pairs;
}
Better:

javascript
function findPairs(arr, sum) {
const seen = new Set();
const pairs = [];
for (const num of arr) {
const complement = sum - num;
if ([Link](complement)) [Link]([complement, num]);
[Link](num);
}
return pairs;
}
Optimal:

javascript
function findPairs(arr, sum) {
[Link]((a, b) => a - b);
let left = 0, right = [Link] - 1;
const pairs = [];
while (left < right) {
const currentSum = arr[left] + arr[right];
if (currentSum === sum) {
[Link]([arr[left], arr[right]]);
left++;
right--;
} else if (currentSum < sum) left++;
else right--;
}
return pairs;
}
9. Unique Triplets That Sum to 0
Brute Force:

javascript
function threeSum(arr) {
const result = [];
for (let i = 0; i < [Link]; i++) {
for (let j = i + 1; j < [Link]; j++) {
for (let k = j + 1; k < [Link]; k++) {
if (arr[i] + arr[j] + arr[k] === 0) {
[Link]([arr[i], arr[j], arr[k]].sort());
}
}
}
}
return [...new Set([Link]([Link]))].map([Link]);
}
Better:

javascript
function threeSum(arr) {
[Link]((a, b) => a - b);
const result = [];
for (let i = 0; i < [Link]; i++) {
if (i > 0 && arr[i] === arr[i - 1]) continue;
let left = i + 1, right = [Link] - 1;
while (left < right) {
const sum = arr[i] + arr[left] + arr[right];
if (sum === 0) {
[Link]([arr[i], arr[left], arr[right]]);
while (left < right && arr[left] === arr[left + 1]) left++;
while (left < right && arr[right] === arr[right - 1]) right--;
left++;
right--;
} else if (sum < 0) left++;
else right--;
}
}
return result;
}
Optimal:

javascript
function threeSum(arr) {
[Link]((a, b) => a - b);
const result = [];
for (let i = 0; i < [Link] - 2; i++) {
if (i > 0 && arr[i] === arr[i - 1]) continue;
const seen = new Set();
for (let j = i + 1; j < [Link]; j++) {
const complement = -arr[i] - arr[j];
if ([Link](complement)) {
[Link]([arr[i], complement, arr[j]]);
while (j + 1 < [Link] && arr[j] === arr[j + 1]) j++;
}
[Link](arr[j]);
}
}
return result;
}
10. Are Two Arrays Anagrams?
Brute Force:

javascript
function areAnagrams(arr1, arr2) {
return [Link]().toString() === [Link]().toString();
}
Better:

javascript
function areAnagrams(arr1, arr2) {
if ([Link] !== [Link]) return false;
const frequency = {};
[Link](item => frequency[item] = (frequency[item] || 0) + 1);
for (const item of arr2) {
if (!frequency[item]) return false;
frequency[item]--;
}
return true;
}
Optimal:

javascript
function areAnagrams(arr1, arr2) {
if ([Link] !== [Link]) return false;
const map = new Map();
[Link](item => [Link](item, ([Link](item) || 0) + 1));
for (const item of arr2) {
if (![Link](item) return false;
[Link](item, [Link](item) - 1);
if ([Link](item) === 0) [Link](item);
}
return [Link] === 0;
}
11. Strings Starting with a Vowel
Brute Force:

javascript
function startsWithVowel(arr) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
return [Link](str => [Link](str[0].toLowerCase()));
}
Better:

javascript
function startsWithVowel(arr) {
return [Link](str => /^[aeiou]/[Link](str));
}
Optimal:

javascript
function startsWithVowel(arr) {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
return [Link](str => [Link](str[0].toLowerCase()));
}
12. Rearrange by String Length
Brute Force:

javascript
function sortByLength(arr) {
return [Link]((a, b) => [Link] - [Link]);
}
Better:

javascript
function sortByLength(arr) {
return [...arr].sort((a, b) => [Link] - [Link]);
}
Optimal:

javascript
function sortByLength(arr) {
return [Link](str => ({ len: [Link], str }))
.sort((a, b) => [Link] - [Link])
.map(obj => [Link]);
}
13. Palindromes Only
Brute Force:

javascript
function palindromesOnly(arr) {
return [Link](str => str === [Link]('').reverse().join(''));
}
Better:

javascript
function palindromesOnly(arr) {
return [Link](str => {
let left = 0, right = [Link] - 1;
while (left < right) {
if (str[left] !== str[right]) return false;
left++;
right--;
}
return true;
});
}
Optimal:

javascript
function palindromesOnly(arr) {
return [Link](str => [...str].every((char, i) => char === str[[Link] - 1 - i]));
}
14. Common Elements in Multiple Arrays
Brute Force:

javascript
function commonElements(arrays) {
return [Link]((acc, curr) =>
[Link](item => [Link](item)));
}
Better:

javascript
function commonElements(arrays) {
const frequency = {};
[Link](arr => {
[...new Set(arr)].forEach(item =>
frequency[item] = (frequency[item] || 0) + 1);
});
return [Link](frequency).filter(key =>
frequency[key] === [Link]);
}
Optimal:

javascript
function commonElements(arrays) {
if ([Link] === 0) return [];
const common = new Set(arrays[0]);
for (let i = 1; i < [Link]; i++) {
const current = new Set(arrays[i]);
for (const item of common) {
if (![Link](item)) [Link](item);
}
}
return [...common];
}
15. Group by First Letter
Brute Force:

javascript
function groupByFirstLetter(arr) {
const result = {};
[Link](str => {
const firstChar = str[0].toLowerCase();
result[firstChar] = (result[firstChar] || []).concat(str);
});
return result;
}
Better:

javascript
function groupByFirstLetter(arr) {
return [Link]((acc, str) => {
const key = str[0].toLowerCase();
acc[key] = (acc[key] || []).concat(str);
return acc;
}, {});
}
Optimal:

javascript
function groupByFirstLetter(arr) {
const map = new Map();
[Link](str => {
const key = str[0].toLowerCase();
[Link](key, ([Link](key) || []).concat(str));
});
return [Link](map);
}
16. Longest Consecutive Sequence
Brute Force:

javascript
function longestConsecutive(nums) {
let max = 0;
for (const num of nums) {
let current = num;
let streak = 1;
while ([Link](current + 1)) {
current++;
streak++;
}
max = [Link](max, streak);
}
return max;
}
Better:

javascript
function longestConsecutive(nums) {
const set = new Set(nums);
let max = 0;
for (const num of set) {
if (![Link](num - 1)) {
let current = num;
let streak = 1;
while ([Link](current + 1)) {
current++;
streak++;
}
max = [Link](max, streak);
}
}
return max;
}
Optimal:

javascript
function longestConsecutive(nums) {
const numSet = new Set(nums);
let longest = 0;
for (const num of numSet) {
if (![Link](num - 1)) {
let current = num;
let currentStreak = 1;
while ([Link](current + 1)) {
current++;
currentStreak++;
}
longest = [Link](longest, currentStreak);
}
}
return longest;
}
17. Subarray with Given Sum
Brute Force:

javascript
function subarraySum(arr, sum) {
for (let i = 0; i < [Link]; i++) {
let currentSum = 0;
for (let j = i; j < [Link]; j++) {
currentSum += arr[j];
if (currentSum === sum) return [Link](i, j + 1);
}
}
return [];
}
Better:

javascript
function subarraySum(arr, sum) {
const prefixSum = { 0: -1 };
let currentSum = 0;
for (let i = 0; i < [Link]; i++) {
currentSum += arr[i];
if ([Link](currentSum - sum)) {
return [Link](prefixSum[currentSum - sum] + 1, i + 1);
}
prefixSum[currentSum] = i;
}
return [];
}
Optimal:

javascript
function subarraySum(arr, sum) {
let left = 0, currentSum = 0;
for (let right = 0; right < [Link]; right++) {
currentSum += arr[right];
while (currentSum > sum && left <= right) {
currentSum -= arr[left];
left++;
}
if (currentSum === sum) return [Link](left, right + 1);
}
return [];
}
18. Index of Element Without indexOf()
Brute Force:

javascript
function indexOf(arr, elem) {
for (let i = 0; i < [Link]; i++) {
if (arr[i] === elem) return i;
}
return -1;
}
Better:

javascript
function indexOf(arr, elem) {
return [Link](item => item === elem);
}
Optimal:

javascript
function indexOf(arr, elem) {
let left = 0, right = [Link] - 1;
while (left <= right) {
if (arr[left] === elem) return left;
if (arr[right] === elem) return right;
left++;
right--;
}
return -1;
}
19. Replace All Occurrences
Brute Force:

javascript
function replaceAll(arr, oldVal, newVal) {
return [Link](item => item === oldVal ? newVal : item);
}
Better:

javascript
function replaceAll(arr, oldVal, newVal) {
return [Link]((acc, item) =>
[...acc, item === oldVal ? newVal : item], []);
}
Optimal:

javascript
function replaceAll(arr, oldVal, newVal) {
for (let i = 0; i < [Link]; i++) {
if (arr[i] === oldVal) arr[i] = newVal;
}
return arr;
}
20. Merge Two Arrays Alternately
Brute Force:

javascript
function mergeAlternate(arr1, arr2) {
const result = [];
const maxLength = [Link]([Link], [Link]);
for (let i = 0; i < maxLength; i++) {
if (i < [Link]) [Link](arr1[i]);
if (i < [Link]) [Link](arr2[i]);
}
return result;
}
Better:

javascript
function mergeAlternate(arr1, arr2) {
return [Link]((item, i) =>
i < [Link] ? [item, arr2[i]] : [item]).concat([Link]([Link]));
}
Optimal:

javascript
function mergeAlternate(arr1, arr2) {
const result = [];
let i = 0;
while (i < [Link] || i < [Link]) {
if (i < [Link]) [Link](arr1[i]);
if (i < [Link]) [Link](arr2[i]);
i++;
}
return result;
}
String Problems
1. Reverse Words in a Sentence
Brute Force:

javascript
function reverseWords(str) {
return [Link](' ').reverse().join(' ');
}
Better:

javascript
function reverseWords(str) {
return [Link]().split(/\s+/).reverse().join(' ');
}
Optimal:

javascript
function reverseWords(str) {
let result = '', word = '';
for (const char of str) {
if (char === ' ') {
if (word) {
result = word + (result ? ' ' + result : '');
word = '';
}
} else word += char;
}
if (word) result = word + (result ? ' ' + result : '');
return result;
}
2. Remove All Duplicate Characters
Brute Force:

javascript
function removeDuplicates(str) {
const seen = new Set();
let result = '';
for (const char of str) {
if (![Link](char)) {
[Link](char);
result += char;
}
}
return result;
}
Better:
javascript
function removeDuplicates(str) {
return [...new Set(str)].join('');
}
Optimal:

javascript
function removeDuplicates(str) {
return [Link]('').filter((char, i) => [Link](char) === i).join('');
}
3. Find First Non-Repeating Character
Brute Force:

javascript
function firstNonRepeatingChar(str) {
for (let i = 0; i < [Link]; i++) {
if ([Link](str[i]) === [Link](str[i])) {
return str[i];
}
}
return null;
}
Better:

javascript
function firstNonRepeatingChar(str) {
const frequency = {};
for (const char of str) {
frequency[char] = (frequency[char] || 0) + 1;
}
for (const char of str) {
if (frequency[char] === 1) return char;
}
return null;
}
Optimal:

javascript
function firstNonRepeatingChar(str) {
const seen = new Map();
for (const [i, char] of [...str].entries()) {
if ([Link](char)) [Link](char, -1);
else [Link](char, i);
}
for (const [char, index] of seen) {
if (index !== -1) return char;
}
return null;
}
4. Check for Anagram (Ignoring Case & Spaces)
Brute Force:

javascript
function isAnagram(str1, str2) {
const clean = s => [Link](/\s/g, '').toLowerCase();
return clean(str1).split('').sort().join('') === clean(str2).split('').sort().join('');
}
Better:

javascript
function isAnagram(str1, str2) {
const clean = s => [Link](/\s/g, '').toLowerCase();
const freq = {};
for (const char of clean(str1)) freq[char] = (freq[char] || 0) + 1;
for (const char of clean(str2)) {
if (!freq[char]) return false;
freq[char]--;
}
return [Link](freq).every(val => val === 0);
}
Optimal:

javascript
function isAnagram(str1, str2) {
const clean = s => [Link](/\s/g, '').toLowerCase();
if (clean(str1).length !== clean(str2).length) return false;
const map = new Map();
for (const char of clean(str1)) [Link](char, ([Link](char) || 0) + 1);
for (const char of clean(str2)) {
if (![Link](char)) return false;
[Link](char, [Link](char) - 1);
if ([Link](char) === 0) [Link](char);
}
return [Link] === 0;
}
5. Count Vowels and Consonants
Brute Force:
javascript
function countVowelsConsonants(str) {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
let vowelCount = 0, consonantCount = 0;
for (const char of [Link]()) {
if (/[a-z]/.test(char)) {
if ([Link](char)) vowelCount++;
else consonantCount++;
}
}
return { vowels: vowelCount, consonants: consonantCount };
}
Better:

javascript
function countVowelsConsonants(str) {
const vowelRegex = /[aeiou]/gi;
const vowels = ([Link](vowelRegex) || [];
const consonants = [Link](/[^a-z]/gi, '').length - [Link];
return { vowels: [Link], consonants };
}
Optimal:

javascript
function countVowelsConsonants(str) {
const vowelSet = new Set(['a', 'e', 'i', 'o', 'u']);
let vowels = 0, consonants = 0;
for (const char of [Link]()) {
if (/[a-z]/.test(char)) {
[Link](char) ? vowels++ : consonants++;
}
}
return { vowels, consonants };
}
6. Longest Word in a Sentence
Brute Force:

javascript
function longestWord(sentence) {
return [Link](' ').reduce((longest, word) =>
[Link] > [Link] ? word : longest, '');
}
Better:
javascript
function longestWord(sentence) {
return [Link](' ').sort((a, b) => [Link] - [Link])[0];
}
Optimal:

javascript
function longestWord(sentence) {
let max = '', current = '';
for (const char of sentence) {
if (char === ' ') {
if ([Link] > [Link]) max = current;
current = '';
} else current += char;
}
return [Link] > [Link] ? current : max;
}
7. Capitalize First Letter of Each Word
Brute Force:

javascript
function capitalizeWords(str) {
return [Link](' ').map(word =>
[Link](0).toUpperCase() + [Link](1)).join(' ');
}
Better:

javascript
function capitalizeWords(str) {
return [Link](/\b\w/g, char => [Link]());
}
Optimal:

javascript
function capitalizeWords(str) {
let result = '';
let capitalize = true;
for (const char of str) {
result += capitalize ? [Link]() : char;
capitalize = char === ' ';
}
return result;
}
8. Check If String is Palindrome (Ignore Non-Alpha)
Brute Force:

javascript
function isPalindrome(str) {
const clean = [Link]().replace(/[^a-z]/g, '');
return clean === [Link]('').reverse().join('');
}
Better:

javascript
function isPalindrome(str) {
const clean = [Link]().replace(/[^a-z]/g, '');
let left = 0, right = [Link] - 1;
while (left < right) {
if (clean[left] !== clean[right]) return false;
left++;
right--;
}
return true;
}
Optimal:

javascript
function isPalindrome(str) {
const isAlpha = c => /[a-z]/[Link](c);
let left = 0, right = [Link] - 1;
while (left < right) {
while (!isAlpha(str[left])) left++;
while (!isAlpha(str[right])) right--;
if (str[left].toLowerCase() !== str[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}
9. Compress Consecutive Characters
Brute Force:

javascript
function compressString(str) {
let result = '', count = 1;
for (let i = 0; i < [Link]; i++) {
if (str[i] === str[i + 1]) count++;
else {
result += str[i] + count;
count = 1;
}
}
return result;
}
Better:

javascript
function compressString(str) {
return [Link](/(.)\1*/g, match => match[0] + [Link]);
}
Optimal:

javascript
function compressString(str) {
if (!str) return '';
let result = '';
let current = str[0], count = 1;
for (let i = 1; i < [Link]; i++) {
if (str[i] === current) count++;
else {
result += current + count;
current = str[i];
count = 1;
}
}
return result + current + count;
}
10. Find All Substrings of a Given String
Brute Force:

javascript
function allSubstrings(str) {
const result = [];
for (let i = 0; i < [Link]; i++) {
for (let j = i + 1; j <= [Link]; j++) {
[Link]([Link](i, j));
}
}
return result;
}
Better:
javascript
function allSubstrings(str) {
return [...str].flatMap((_, i) =>
[...str].map((_, j) => [Link](i, j + 1)).filter(s => s);
}
Optimal:

javascript
function allSubstrings(str) {
return [Link]({ length: [Link] }, (_, i) =>
[Link]({ length: [Link] - i }, (_, j) =>
[Link](i, i + j + 1))).flat();
}
11. Count Occurrences of a Word
Brute Force:

javascript
function countWordOccurrences(sentence, word) {
return [Link](' ').filter(w => w === word).length;
}
Better:

javascript
function countWordOccurrences(sentence, word) {
return ([Link](new RegExp(`\\b${word}\\b`, 'gi')) || []).length;
}
Optimal:

javascript
function countWordOccurrences(sentence, word) {
let count = 0, index = 0;
while ((index = [Link](word, index)) !== -1) {
count++;
index += [Link];
}
return count;
}
12. Replace All Digits with Dashes
Brute Force:

javascript
function replaceDigits(str) {
return [Link](/[0-9]/g, '-');
}
Better:

javascript
function replaceDigits(str) {
return [...str].map(c => /\d/.test(c) ? '-' : c).join('');
}
Optimal:

javascript
function replaceDigits(str) {
let result = '';
for (const char of str) {
result += char >= '0' && char <= '9' ? '-' : char;
}
return result;
}
13. Remove Characters Present in Another String
Brute Force:

javascript
function removeChars(str1, str2) {
const toRemove = new Set(str2);
return [...str1].filter(c => ![Link](c)).join('');
}
Better:

javascript
function removeChars(str1, str2) {
return [Link](new RegExp(`[${str2}]`, 'g'), '');
}
Optimal:

javascript
function removeChars(str1, str2) {
const toRemove = {};
for (const char of str2) toRemove[char] = true;
let result = '';
for (const char of str1) {
if (!toRemove[char]) result += char;
}
return result;
}
14. Toggle Case of Each Letter
Brute Force:

javascript
function toggleCase(str) {
return [Link]('').map(c =>
c === [Link]() ? [Link]() : [Link]()).join('');
}
Better:

javascript
function toggleCase(str) {
return [Link](/[a-z]/gi, c =>
c === [Link]() ? [Link]() : [Link]());
}
Optimal:

javascript
function toggleCase(str) {
let result = '';
for (const char of str) {
const code = [Link](0);
if (code >= 65 && code <= 90) result += [Link](code + 32);
else if (code >= 97 && code <= 122) result += [Link](code - 32);
else result += char;
}
return result;
}
15. Most Frequent Character
Brute Force:

javascript
function mostFrequentChar(str) {
const frequency = {};
for (const char of str) frequency[char] = (frequency[char] || 0) + 1;
return [Link](frequency).sort((a, b) => b[1] - a[1])[0][0];
}
Better:

javascript
function mostFrequentChar(str) {
const frequency = [...str].reduce((acc, char) =>
(acc[char] = (acc[char] || 0) + 1, acc), {});
return [Link](frequency).reduce((a, b) =>
frequency[a] >= frequency[b] ? a : b);
}
Optimal:

javascript
function mostFrequentChar(str) {
const frequency = new Map();
let maxChar = '', maxCount = 0;
for (const char of str) {
const count = ([Link](char) || 0) + 1;
[Link](char, count);
if (count > maxCount) {
maxCount = count;
maxChar = char;
}
}
return maxChar;
}
16. Remove All White Spaces
Brute Force:

javascript
function removeWhitespace(str) {
return [Link](/\s/g, '');
}
Better:

javascript
function removeWhitespace(str) {
return [Link](' ').join('');
}
Optimal:

javascript
function removeWhitespace(str) {
let result = '';
for (const char of str) {
if (char !== ' ' && char !== '\t' && char !== '\n') result += char;
}
return result;
}
17. Find All Duplicates
Brute Force:

javascript
function findDuplicates(str) {
const frequency = {};
const duplicates = [];
for (const char of str) {
frequency[char] = (frequency[char] || 0) + 1;
if (frequency[char] === 2) [Link](char);
}
return duplicates;
}
Better:

javascript
function findDuplicates(str) {
return [...str].filter((char, i) => [Link](char) !== i);
}
Optimal:

javascript
function findDuplicates(str) {
const seen = new Set();
const duplicates = new Set();
for (const char of str) {
if ([Link](char)) [Link](char);
else [Link](char);
}
return [...duplicates];
}
18. Find Common Characters Between Two Strings
Brute Force:

javascript
function commonChars(str1, str2) {
const set2 = new Set(str2);
return [...new Set(str1)].filter(char => [Link](char));
}
Better:

javascript
function commonChars(str1, str2) {
const freq1 = {};
const freq2 = {};
for (const char of str1) freq1[char] = (freq1[char] || 0) + 1;
for (const char of str2) freq2[char] = (freq2[char] || 0) + 1;
return [Link](freq1).filter(char => freq2[char]);
}
Optimal:

javascript
function commonChars(str1, str2) {
const set1 = new Set(str1);
const set2 = new Set(str2);
return [...set1].filter(char => [Link](char));
}
19. Remove Duplicate Words from Sentence
Brute Force:

javascript
function removeDuplicateWords(sentence) {
const seen = new Set();
return [Link](' ').filter(word => {
if ([Link](word)) return false;
[Link](word);
return true;
}).join(' ');
}
Better:

javascript
function removeDuplicateWords(sentence) {
return [...new Set([Link](' '))].join(' ');
}
Optimal:

javascript
function removeDuplicateWords(sentence) {
const words = [Link](' ');
const seen = {};
let result = [];
for (const word of words) {
if (!seen[word]) {
seen[word] = true;
[Link](word);
}
}
return [Link](' ');
}
20. Shift Characters by N (Caesar Cipher Basic)
Brute Force:
javascript
function caesarCipher(str, n) {
return [Link]('').map(c => {
const code = [Link](0);
if (code >= 65 && code <= 90) {
return [Link](((code - 65 + n) % 26) + 65);
} else if (code >= 97 && code <= 122) {
return [Link](((code - 97 + n) % 26) + 97);
}
return c;
}).join('');
}
Better:

javascript
function caesarCipher(str, n) {
return [Link](/[a-z]/gi, c => {
const base = c === [Link]() ? 65 : 97;
return [Link](([Link](0) - base + n) % 26 + base);
});
}
Optimal:

javascript
function caesarCipher(str, n) {
let result = '';
n = n % 26;
for (const char of str) {
const code = [Link](0);
if (code >= 65 && code <= 90) {
result += [Link](((code - 65 + n + 26) % 26) + 65);
} else if (code >= 97 && code <= 122) {
result += [Link](((code - 97 + n + 26) % 26) + 97);
} else result += char;
}
return result;
}
Object-Based Problems
1. Filter Object Keys by Value Type
Brute Force:

javascript
function filterKeysByType(obj, type) {
return [Link](obj).filter(key => typeof obj[key] === type);
}
Better:

javascript
function filterKeysByType(obj, type) {
return [Link](obj)
.filter(([key, value]) => typeof value === type)
.map(([key]) => key);
}
Optimal:

javascript
function filterKeysByType(obj, type) {
const result = [];
for (const key in obj) {
if (typeof obj[key] === type) [Link](key);
}
return result;
}
2. Merge Two Objects Without Overwriting
Brute Force:

javascript
function mergeNoOverwrite(obj1, obj2) {
return { ...obj2, ...obj1 };
}
Better:

javascript
function mergeNoOverwrite(obj1, obj2) {
const result = {};
for (const key in obj1) result[key] = obj1[key];
for (const key in obj2) {
if (!(key in result)) result[key] = obj2[key];
}
return result;
}
Optimal:

javascript
function mergeNoOverwrite(obj1, obj2) {
return [Link]({}, obj2, obj1);
}
3. Invert an Object
Brute Force:

javascript
function invertObject(obj) {
const result = {};
for (const key in obj) {
result[obj[key]] = key;
}
return result;
}
Better:

javascript
function invertObject(obj) {
return [Link]([Link](obj).map(([k, v]) => [v, k]));
}
Optimal:

javascript
function invertObject(obj) {
const result = {};
[Link](obj).forEach(key => result[obj[key]] = key);
return result;
}
4. Group Objects by a Property
Brute Force:

javascript
function groupBy(arr, key) {
const result = {};
[Link](item => {
const groupKey = item[key];
if (!result[groupKey]) result[groupKey] = [];
result[groupKey].push(item);
});
return result;
}
Better:

javascript
function groupBy(arr, key) {
return [Link]((acc, item) => {
const groupKey = item[key];
acc[groupKey] = (acc[groupKey] || []).concat(item);
return acc;
}, {});
}
Optimal:

javascript
function groupBy(arr, key) {
const result = new Map();
[Link](item => {
const groupKey = item[key];
if (![Link](groupKey)) [Link](groupKey, []);
[Link](groupKey).push(item);
});
return [Link](result);
}
5. Convert Object to Array of Key-Value Pairs
Brute Force:

javascript
function objectToArray(obj) {
return [Link](obj).map(key => [key, obj[key]]);
}
Better:

javascript
function objectToArray(obj) {
return [Link](obj);
}
Optimal:

javascript
function objectToArray(obj) {
const result = [];
for (const key in obj) {
[Link]([key, obj[key]]);
}
return result;
}
6. Compare Two Objects for Deep Equality
Brute Force:

javascript
function deepEqual(obj1, obj2) {
return [Link](obj1) === [Link](obj2);
}
Better:

javascript
function deepEqual(obj1, obj2) {
if (typeof obj1 !== typeof obj2) return false;
if (typeof obj1 !== 'object' || obj1 === null || obj2 === null) {
return obj1 === obj2;
}
const keys1 = [Link](obj1), keys2 = [Link](obj2);
if ([Link] !== [Link]) return false;
for (const key of keys1) {
if (![Link](key) return false;
if (!deepEqual(obj1[key], obj2[key])) return false;
}
return true;
}
Optimal:

javascript
function deepEqual(a, b) {
if (a === b) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
return false;
}
const aKeys = [Link](a), bKeys = [Link](b);
if ([Link] !== [Link]) return false;
for (const key of aKeys) {
if (![Link](key)) return false;
if (!deepEqual(a[key], b[key])) return false;
}
return true;
}
7. Find Duplicate Values Across Objects in Array
Brute Force:

javascript
function findDuplicateValues(arr) {
const frequency = {};
[Link](obj => {
[Link](obj).forEach(val => {
frequency[val] = (frequency[val] || 0) + 1;
});
});
return [Link](frequency).filter(key => frequency[key] > 1);
}
Better:

javascript
function findDuplicateValues(arr) {
const seen = new Set();
const duplicates = new Set();
[Link](obj => {
[Link](obj).forEach(val => {
if ([Link](val)) [Link](val);
else [Link](val);
});
});
return [...duplicates];
}
Optimal:

javascript
function findDuplicateValues(arr) {
const valueCount = new Map();
const duplicates = new Set();
for (const obj of arr) {
for (const val of [Link](obj)) {
const count = ([Link](val) || 0) + 1;
[Link](val, count);
if (count > 1) [Link](val);
}
}
return [...duplicates];
}
8. Remove Keys with Null or Undefined Values
Brute Force:

javascript
function removeNullUndefined(obj) {
const result = {};
for (const key in obj) {
if (obj[key] != null) result[key] = obj[key];
}
return result;
}
Better:
javascript
function removeNullUndefined(obj) {
return [Link](
[Link](obj).filter(([key, value]) => value != null)
);
}
Optimal:

javascript
function removeNullUndefined(obj) {
const result = { ...obj };
for (const key in result) {
if (result[key] == null) delete result[key];
}
return result;
}
9. Count Frequency of Each Value in Object Array
Brute Force:

javascript
function countValueFrequency(arr, key) {
const frequency = {};
[Link](obj => {
const val = obj[key];
frequency[val] = (frequency[val] || 0) + 1;
});
return frequency;
}
Better:

javascript
function countValueFrequency(arr, key) {
return [Link]((acc, obj) => {
const val = obj[key];
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
}
Optimal:

javascript
function countValueFrequency(arr, key) {
const frequency = new Map();
for (const obj of arr) {
const val = obj[key];
[Link](val, ([Link](val) || 0) + 1);
}
return [Link](frequency);
}
10. Rename Keys in an Object Based on Map
Brute Force:

javascript
function renameKeys(obj, keyMap) {
const result = {};
for (const oldKey in obj) {
const newKey = keyMap[oldKey] || oldKey;
result[newKey] = obj[oldKey];
}
return result;
}
Better:

javascript
function renameKeys(obj, keyMap) {
return [Link](
[Link](obj).map(([key, value]) => [keyMap[key] || key, value])
);
}
Optimal:

javascript
function renameKeys(obj, keyMap) {
const result = {};
[Link](obj).forEach(oldKey => {
result[keyMap[oldKey] || oldKey] = obj[oldKey];
});
return result;
}
11. Find Intersection of Object Keys
Brute Force:

javascript
function commonKeys(obj1, obj2) {
return [Link](obj1).filter(key => key in obj2);
}
Better:
javascript
function commonKeys(obj1, obj2) {
const keys1 = new Set([Link](obj1));
return [Link](obj2).filter(key => [Link](key));
}
Optimal:

javascript
function commonKeys(obj1, obj2) {
const result = [];
for (const key in obj1) {
if (key in obj2) [Link](key);
}
return result;
}
12. Sort Object by Value (Ascending)
Brute Force:

javascript
function sortObjectByValue(obj) {
return [Link](obj).sort((a, b) => a[1] - b[1]);
}
Better:

javascript
function sortObjectByValue(obj) {
return [Link]([Link](obj).sort((a, b) => a[1] - b[1]));
}
Optimal:

javascript
function sortObjectByValue(obj) {
const sorted = [];
for (const key in obj) {
[Link]([key, obj[key]]);
}
[Link]((a, b) => a[1] - b[1]);
return sorted;
}
13. Convert Query String to Object
Brute Force:

javascript
function queryStringToObject(query) {
return [Link]('&').reduce((acc, pair) => {
const [key, value] = [Link]('=');
acc[key] = value;
return acc;
}, {});
}
Better:

javascript
function queryStringToObject(query) {
return [Link](new URLSearchParams(query));
}
Optimal:

javascript
function queryStringToObject(query) {
const result = {};
[Link]('&').forEach(pair => {
const [key, value] = [Link]('=');
if (key) result[key] = value;
});
return result;
}
14. Validate Required Object Keys
Brute Force:

javascript
function hasRequiredKeys(obj, required) {
return [Link](key => key in obj);
}
Better:

javascript
function hasRequiredKeys(obj, required) {
const keys = new Set([Link](obj));
return [Link](key => [Link](key));
}
Optimal:

javascript
function hasRequiredKeys(obj, required) {
for (const key of required) {
if (!(key in obj)) return false;
}
return true;
}
15. Find Keys with Numeric Values Only
Brute Force:

javascript
function numericKeys(obj) {
return [Link](obj).filter(key => typeof obj[key] === 'number');
}
Better:

javascript
function numericKeys(obj) {
return [Link](obj)
.filter(([key, value]) => typeof value === 'number')
.map(([key]) => key);
}
Optimal:

javascript
function numericKeys(obj) {
const result = [];
for (const key in obj) {
if (typeof obj[key] === 'number') [Link](key);
}
return result;
}
16. Group Object Keys by Value Type
Brute Force:

javascript
function groupKeysByType(obj) {
const result = {};
for (const key in obj) {
const type = typeof obj[key];
if (!result[type]) result[type] = [];
result[type].push(key);
}
return result;
}
Better:

javascript
function groupKeysByType(obj) {
return [Link](obj).reduce((acc, [key, value]) => {
const type = typeof value;
acc[type] = (acc[type] || []).concat(key);
return acc;
}, {});
}
Optimal:

javascript
function groupKeysByType(obj) {
const result = {};
[Link](obj).forEach(key => {
const type = typeof obj[key];
result[type] ? result[type].push(key) : (result[type] = [key]);
});
return result;
}
17. Serialize Nested Object into Dot Notation
Brute Force:

javascript
function flattenObject(obj, prefix = '') {
let result = {};
for (const key in obj) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
[Link](result, flattenObject(obj[key], newKey));
} else {
result[newKey] = obj[key];
}
}
return result;
}
Better:

javascript
function flattenObject(obj, prefix = '') {
return [Link](obj).reduce((acc, [key, value]) => {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof value === 'object' && value !== null) {
[Link](acc, flattenObject(value, newKey));
} else {
acc[newKey] = value;
}
return acc;
}, {});
}
Optimal:

javascript
function flattenObject(obj, prefix = '') {
const result = {};
for (const key in obj) {
const fullKey = prefix ? `${prefix}.${key}` : key;
const value = obj[key];
if (typeof value === 'object' && value !== null && ![Link](value)) {
[Link](result, flattenObject(value, fullKey));
} else {
result[fullKey] = value;
}
}
return result;
}
18. Clone Object Deeply
Brute Force:

javascript
function deepClone(obj) {
return [Link]([Link](obj));
}
Better:

javascript
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
const clone = [Link](obj) ? [] : {};
for (const key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}
Optimal:

javascript
function deepClone(obj, cache = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if ([Link](obj)) return [Link](obj);
const clone = [Link](obj) ? [] : {};
[Link](obj, clone);
for (const key in obj) {
if ([Link](key)) {
clone[key] = deepClone(obj[key], cache);
}
}
return clone;
}
19. Replace Values in Object by Rule
Brute Force:

javascript
function replaceValues(obj, rule) {
const result = {};
for (const key in obj) {
result[key] = rule(obj[key]);
}
return result;
}
Better:

javascript
function replaceValues(obj, rule) {
return [Link](
[Link](obj).map(([key, value]) => [key, rule(value)])
);
}
Optimal:

javascript
function replaceValues(obj, rule) {
const result = { ...obj };
for (const key in result) {
result[key] = rule(result[key]);
}
return result;
}
20. Sum All Numeric Values in Object
Brute Force:

javascript
function sumNumericValues(obj) {
let sum = 0;
for (const key in obj) {
if (typeof obj[key] === 'number') sum += obj[key];
}
return sum;
}
Better:

javascript
function sumNumericValues(obj) {
return [Link](obj)
.filter(val => typeof val === 'number')
.reduce((sum, num) => sum + num, 0);
}
Optimal:

javascript
function sumNumericValues(obj) {
let sum = 0;
for (const val of [Link](obj)) {
if (typeof val === 'number') sum += val;
}
return sum;
}

You might also like