Js - Sorting
I had an interview with a Chennai-based marketing company. It was an interactive session and lasted for an hour, which was very engaging. The nice thing was that the questions were mainly fundamental. I was asked to remove a comma from a string. I was coding in a basic way, but he expected me to use regex. As the interview went smoothly, we got deeper, but I didn’t have any idea on one of the questions.
One such question was, “How does React Router work behind the scenes?” I answered from a React perspective, but the expectation was related to browser history mechanics like push and pop operations. Later, I realized what the interviewer was actually expecting.
Then I was given another question: to print the missing numbers from an array. The input and output were as follows:
I/P: [5, 2, 9, 1, 5, 6]
O/P: [3, 4, 7, 8]
I explained that the first step is to sort the array, then find the min and max values. Based on this range, we loop through the values and check whether each number is present in the array. To check if a number exists, I used indexOf, and if the result was -1, I pushed the number into a new array. That’s how I coded it.
At that point, I realized that all libraries and frameworks actually work on top of JavaScript. This is what the interviewer was expecting.
I tried to implement the same thing after the interview. It wasn’t perfect or optimized, but I enjoyed coding it.
Here it is:
// To find the missing numbers from the array
const array = [5, 2, 9, 1, 5, 6];
const computedArray = [];
// Sort the data
array.map((data) => {
if (computedArray && computedArray.length) {
computedArray.map((iData, iIndex) => {
if (iData > data) {
computedArray.splice(iIndex, 0, data);
} else {
computedArray.push(data);
}
});
} else {
computedArray.push(data);
}
});
// Remove duplicates if any
const removedDuplicateData = [];
for (let i = 0; i <= computedArray.length - 1; i++) {
let index = removedDuplicateData.indexOf(computedArray[i]);
if (index === -1) {
removedDuplicateData.push(computedArray[i]);
}
}
// Find Min and Max
const min = removedDuplicateData[0];
const max = removedDuplicateData[removedDuplicateData.length - 1];
const missingValue = [];
const sequence = [];
for (let i = min; i <= max; i++) {
sequence.push(i);
let index = removedDuplicateData.indexOf(i);
if (index === -1 && index !== 0) {
missingValue.push(i);
}
}
console.log("missingValue", missingValue);
console.log("sequence", sequence);