Ticker

6/recent/ticker-posts

JavaScript Logic Questions Every Developer Should Practice:whosgeek

JavaScript Logic Questions Every Developer Should Practicewhosgeek



 Palindrome Check

A palindrome is a word, number, or string that reads the same forward and backward.

Examples

  • "abba" → Palindrome ✅

  • "madam" → Palindrome ✅

  • "seggfcew" → Not a palindrome ❌

In technical interviews and DSA (Data Structures and Algorithms) practice, checking whether a string is a palindrome is one of the most common questions.

Let’s understand the different approaches used in the code.

1. Palindrome Check Using Manual String Reversal

let str = 'abba'

let str2 = ""

for (let value of str) {

    str2 = value + str2

}

console.log(str2)

How this works

  1. str contains the original string (abba).

  2. str2 starts as an empty string.

  3. We loop through every character in str.

  4. Instead of adding characters at the end, we add them at the beginning of str2.

2. Comparing Original and Reversed String

let ispalindrome = true;

for (let i = 0; i < str.length; i++) {

    if (str[i] != str2[i]) {

        ispalindrome = false

    }

}

console.log(ispalindrome)


Explanation

Now we compare the original string and the reversed string.

Steps:

  1. Start with ispalindrome = true

  2. Compare each character of both strings

  3. If any character is different → set ispalindrome = false


3. Palindrome Using JavaScript Built-in Methods

JavaScript already provides built-in functions to make this easier.

let str3 = (str) => {

    let str2 = str.split("").reverse().join("");

    return str2 === str

}

Explanation

This method uses three JavaScript functions:

1. split("")

Converts the string into an array.

"abba" → ["a","b","b","a"]

2. reverse()

Reverses the array.

["a","b","b","a"] → ["a","b","b","a"]

3. join("")

Joins the array back into a string.

["a","b","b","a"] → "abba"

Then we compare:

reversedString === originalString

If they are equal → Palindrome


4. Palindrome Check Using an IIFE Function

(function (str) {
let reversed = '';
for (let x of str) {
reversed = x + reversed
}
console.log(reversed === str)
})("abba")

What is happening here?

This is called an IIFE (Immediately Invoked Function Expression).

It means the function runs immediately after being created.

Steps:

  1. The function receives "abba" as input.

  2. It reverses the string using the same logic (x + reversed).

  3. Then it checks:

reversed === str

If both are the same → true


Time Complexity

For all approaches:

Time Complexity: O(n)

Because we must check every character at least once.

-------------------------------------------------------------------------

Question: Find the Most Frequent Character in a String.

In JavaScript interviews, a very common logic question is:

Find the character that appears the most in a string.

For example:

Input: aabbbccccc
Output: c appeared : 5 times

This means the character "c" occurs the most times in the string.

Let’s understand the solution step-by-step.

let result = (string) => {
let obj = {};

for (let value of string)
obj[value] ? obj[value]++ : obj[value] = 1

let num = 0
let str4 = ''

for (value in obj) {
if (obj[value] >= num) {
num = obj[value]
str4 = value
}
}

return `${str4} appeared : ${num} times`
}

let str = 'aabbbccccc'
console.log(result(str))

Step 1: Create an Object to Store Counts

let obj = {};

We create an empty object to store how many times each character appears.

Example:

aabbbccccc

After counting, the object will look like this:

{
a: 2,
b: 3,
c: 5
}

Step 2: Count Each Character

for (let value of string)
obj[value] ? obj[value]++ : obj[value] = 1

This loop goes through each character in the string.

Logic:

  • If the character already exists in the object → increase the count.

  • If it does not exist → create it with value 1.


Step 3: Find the Highest Occurrence

let num = 0
let str4 = ''
  • num → stores the maximum count

  • str4 → stores the character with highest frequency


Step 4: Loop Through Object

for (value in obj) {
if (obj[value] >= num) {
num = obj[value]
str4 = value
}
}

This loop checks each key in the object.

If the current character count is greater than the previous maximum, we update:

num = new highest count
str4 = corresponding character

Step 5: Return the Result

return `${str4} appeared : ${num} times`

Final output:

c appeared : 5 times

Output

c appeared : 5 times

--------------------------------------------------------

Array Chunking (Split an Array into Smaller Arrays)

A common JavaScript interview question is:

Write a function that splits an array into smaller arrays of a given size.

This technique is called array chunking.

For example, if we have an array and we want to divide it into groups of n elements

Example 1

Input:
[1,2,3,4,5,6,7,8,9], n = 3

Output:
[[1,2,3],[4,5,6],[7,8,9]]

The array is divided into groups of 3 elements.

Example 2

Input:
[1,2,3,4,5,6,7,8], n = 7

Output:
[[1,2,3,4,5,6,7],[8]]

Here the last group has only one element left, so it becomes a smaller chunk.

JavaScript Code

function sol2(arr, n) {
let arr2 = [];
let arr3 = [];
let j = 0;

for (let i = 0; i < arr.length; i++) {
arr2.push(arr[i]);
j++;

if (j == n) {
arr3.push(arr2);
arr2 = [];
j = 0;
}
}

if (arr2.length) {
arr3.push(arr2)
}

return arr3
}

let result2 = sol2([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
console.log(result2)

Step-by-Step Explanation

1. Create Two Arrays

let arr2 = [];
let arr3 = [];
  • arr2 → temporary array to store each chunk

  • arr3 → final array that will contain all chunks

Example final result:

[[1,2,3],[4,5,6],[7,8,9]]

2.Loop Through the Array

for (let i = 0; i < arr.length; i++)

We loop through every element of the original array.

3. Add Elements to the Temporary Chunk

arr2.push(arr[i])

Each element is added to arr2.

Example process:

arr2 → [1]
arr2 → [1,2]
arr2 → [1,2,3]

4. Check if Chunk Size Reaches n

if (j == n)

When the temporary array reaches size n:

  1. Push it to the final array

  2. Reset the temporary array

arr3.push(arr2)
arr2 = []
j = 0

Now the next chunk starts.

5. Handle Remaining Elements

Sometimes the array length is not perfectly divisible by n.

Example:

[1,2,3,4,5,6,7,8]

The last element 8 remains.

So we check:

if (arr2.length) {
arr3.push(arr2)
}

This ensures the remaining elements are also added.

Final Output

[[1,2,3],[4,5,6],[7,8,9]]

Time Complexity

O(n)

--------------------------------------------------------------------------

Q:) Check if Two Strings Are Permutations of Each Other

A common JavaScript logic interview question is:

Given two strings, check whether one string is a permutation of the other.

What is a Permutation?

A permutation means both strings contain the same characters with the same frequency, but the order may be different.

Example

Input:
str1 = "abc"
str2 = "cba"

Output:
true

Because both strings contain the same characters.

Another example:

Input:
str1 = "hello"
str2 = "helol"

Output:
true

But:

Input:
str1 = "hello"
str2 = "world"

Output:
false

Because the characters are different.


JavaScript Code

function sol(str1, str2) {
let obj = {}

if (str1.length != str2.length) {
return false
}

for (let i of str1) {
obj[i] ? obj[i]++ : obj[i] = 1
}

result1 = true

for (let i of str2) {
obj[i] ? obj[i]-- : result1 = false
}

return result1
}

let result = sol('qwert12', 'qwert12')
console.log(result)

Step-by-Step Explanation

1. Check String Length

if (str1.length != str2.length) {
return false
}

If the lengths are different, the strings cannot be permutations.

Example:

"abc" vs "abcd"

These can never be permutations because the number of characters is different.


2. Create an Object to Count Characters

let obj = {}

We use an object to store how many times each character appears.

Example:

str1 = "hello"

The object will look like this:

{
h:1,
e:1,
l:2,
o:1
}

3. Count Characters of First String

for (let i of str1) {
obj[i] ? obj[i]++ : obj[i] = 1
}

This loop goes through every character of str1.

Logic:

  • If the character already exists → increase the count.

  • If not → create a new entry

Example result:

{
q:1,
w:1,
e:1,
r:1,
t:1,
1:1,
2:1
}

4. Compare Characters with Second String

for (let i of str2) {
obj[i] ? obj[i]-- : result1 = false
}

Now we loop through str2.

If the character exists in the object:

reduce the count

If it doesn't exist:

result1 = false

This means the strings are not permutations.


5. Return the Result

return result1

If all counts match correctly, the function returns:

true

Otherwise:

false

Example Output

true

Because both strings contain the same characters with the same frequency.


Time Complexity

O(n)

---------------------------------------------------------------

Check and Sort an Array Using Recursion

In many JavaScript coding interviews, you may be asked to check whether an array is sorted and sort it if it is not.

In this example, we use recursion and swapping to sort an array.

The idea is simple:

  1. First check if the array is already sorted.

  2. If it is not sorted, compare two elements.

  3. Swap them if they are in the wrong order.

  4. Repeat the process until the array becomes sorted.


Example Array

[2, 3, 1, 5, 9, 101, 4]

After sorting, it should become:

[1,2,3,4,5,9,101]

JavaScript Code

let i = 0;
let j = 1;
let array = [2, 3, 1, 5, 9, 101, 4];
let array2 = [];

function check(array) {
for (let i = 0; i < array.length; i++) {
if (array[i] > array[i + 1]) {
console.log(array[i]);
return false;
}
}
return true;
}

function sortCheck(arr) {
if (check(array)) {
array2 = array;
return;
}
else if (arr[i] < arr[j]) {
i++;
j++;
sortCheck(arr)
}
else {
[arr[i], arr[j]] = [arr[j], arr[i]]
i = 0;
j = 1;
sortCheck(arr)
}
}

sortCheck(array);

Step-by-Step Explanation

1. Two Index Variables

let i = 0;
let j = 1;

These variables are used to compare two elements in the array.

Example comparison:

array[i] vs array[j]

Example:

2 vs 3
3 vs 1
1 vs 5

2. Function to Check if the Array Is Sorted

function check(array)

This function loops through the array and checks if any element is greater than the next element.

if (array[i] > array[i + 1])

If this happens, it means the array is not sorted.

Example:

3 > 1

So the function returns:

false

If no such condition is found, the array is already sorted.

Then it returns:

true

3. Recursive Sorting Function

function sortCheck(arr)

This function keeps checking and sorting the array until it becomes sorted.


4. If the Array Is Already Sorted

if (check(array)) {
array2 = array;
return;
}

If the array is sorted, we simply store it in array2 and stop the recursion.


5. Compare Two Elements

else if (arr[i] < arr[j])

If the first element is smaller than the second, then the order is correct.

So we simply move forward:

i++
j++

6. Swap Elements if They Are in the Wrong Order

If the elements are not in the correct order:

[arr[i], arr[j]] = [arr[j], arr[i]]

This swaps the two values.

Example:

3 , 1

After swap:

1 , 3

7. Restart the Checking Process

After swapping, we reset the indexes:

i = 0
j = 1

This ensures we check the array again from the beginning.


Final Result

After multiple recursive checks and swaps, the array becomes:

[1,2,3,4,5,9,101]

-----------------------------------------------------------------

Bubble Sort – Simple Explanation

Sorting is one of the most common tasks in programming. Sometimes we need to arrange numbers in ascending order (smallest to largest) or descending order.

One of the easiest sorting techniques to understand is Bubble Sort. In this article, we will explain Bubble Sort using a simple JavaScript example.


The Code

function sol(arr) {
for (let i = arr.length; i > 0; i--) {
console.log(i)

for (let j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
}
}
}
return arr
}

let array = [4, 3, 7, 5, 9, 6];
const res = sol(array);
console.log(res);

Understanding the Logic Step by Step

1. The Function

function sol(arr)

This function takes an array of numbers as input and returns the sorted array.

Example input:

[4, 3, 7, 5, 9, 6]

2. Outer Loop

for (let i = arr.length; i > 0; i--)

This loop controls how many passes the algorithm makes through the array.

If the array length is 6, the loop runs:

6 → 5 → 4 → 3 → 2 → 1

Each pass pushes the largest number to the end of the array.

Think of it like bubbles in water — larger numbers bubble up to the top (end of array).


3. Inner Loop

for (let j = 0; j < i; j++)

This loop compares adjacent elements in the array.

Example comparisons:

4 and 3
3 and 7
7 and 5
5 and 9
9 and 6

4. Swapping Elements

if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
}

If the left number is bigger than the right number, they swap places.

Example:

4 > 3 → swap

Array becomes:

[3, 4, 7, 5, 9, 6]

This continues until the largest element moves to the end.


5. Final Result

After all passes, the array becomes:

[3, 4, 5, 6, 7, 9]

-----------------------------------------------------

Finding the First Pair Whose Sum is Zero

Sometimes in programming problems we need to find two numbers in an array whose sum equals zero.

Example array:

[-5, -4, -3, -2, 0, 2, 4, 6, 8]

Expected output:

[-4, 4]

This means we are looking for the first pair of numbers whose sum is 0.


Code

function sol12(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == 0) {
return [arr[i], arr[j]]
}
}
}
}

How the Logic Works

Step 1: Outer Loop

for (let i = 0; i < arr.length; i++)

This loop selects the first number from the array.

Example:

i = -5
i = -4
i = -3

Step 2: Inner Loop

for (let j = i + 1; j < arr.length; j++)

This loop checks the remaining numbers in the array to form a pair.

So if i = -4, the loop checks:

-4 + -3
-4 + -2
-4 + 0
-4 + 2
-4 + 4

Step 3: Check Sum

if (arr[i] + arr[j] == 0)

If the sum becomes zero, the function returns that pair.

Example:

-4 + 4 = 0

So the output becomes:

[-4, 4]

Time Complexity

This approach checks every pair, so the time complexity is:

O(n²)

This method works but is not very efficient for large arrays.


2. Sorting an Array Using Bubble Sort Logic

The second code snippet sorts an array using a technique similar to the Bubble Sort Algorithm.


Code

function sort(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
for (let j = 0; j < arr.length; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
break
}
}
}
}
sort([6, 22, 9, 3, -7, 8, 4, 5, 1])

How It Works

Step 1: Compare Adjacent Numbers

The code compares two neighboring elements.

Example:

6 and 22
22 and 9
9 and 3

Step 2: Swap if Needed

if (arr[j] > arr[j + 1])

If the left number is bigger, they swap.

Example:

9 > 3 → swap

Array becomes:

[6, 22, 3, 9, -7, 8, 4, 5, 1]

Step 3: Continue the Process

This process repeats until the numbers gradually move into their correct sorted positions.

Final sorted array:

[-7, 1, 3, 4, 5, 6, 8, 9, 22]

3. Finding Zero Sum Pair Using Two Pointer Method

The third approach is much more efficient.
It uses the Two Pointer Technique.

This method works best when the array is already sorted.


Code

function sol2(arr) {
let left = 0
let right = arr.length - 1

while (left < right) {
if (arr[left] + arr[right] == 0) {
return [arr[left], arr[right]]
}
else if (arr[left] + arr[right] > 0) {
right = right - 1
}
else {
left = left + 1
}
}
}

How the Two Pointer Logic Works

Step 1: Start From Both Ends

left = start of array
right = end of array

Example:

[-5, -4, -3, -2, 0, 2, 4, 6, 8]
L R

Step 2: Check the Sum

arr[left] + arr[right]

Example:

-5 + 8 = 3

Since the sum is greater than 0, we move the right pointer left.


Step 3: Move Pointers

If sum > 0

right--

If sum < 0

left++

Eventually we reach:

-4 + 4 = 0

Output:

[-4, 4]

Time Complexity

This method is much faster:

O(n)

Compared to the previous O(n²) approach.


Post a Comment

0 Comments