Skip to main content

Command Palette

Search for a command to run...

Flattening an array and little more.

Published
2 min read
Flattening an array and little more.

Interviewing coders requires smart and insightful questions to differentiate between those who truly understand coding concepts and those who rely solely on memorised answers. Below are a series of array manipulation questions designed to challenge candidates, complete with explanations and code examples.

I usually believe to put easy questions first and slowly increase the complexity of questions so that candidate feel confident and also warmed up.

Question 1: Basic Array Flattening

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

function flattenArray(arr) {
  return arr.reduce((acc, val) => {
    return Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val);
  }, []);
}

// Example usage
let input = [[1, 2], [3, [4, [5, 6]]], 7];
console.log(flattenArray(input)); // Output: [1, 2, 3, 4, 5, 6, 7]

Question 2: Flattening While Tracking Nesting Levels

Input: [[1, 2], [3, [4, [5, 6]]], 7]
Output: ['1-1', '2-1', '3-1', '4-2', '5-3', '6-3', '7-0']

function flattenWithLevels(arr, level = 0) {
  let result = [];
  arr.forEach(item => {
    if (Array.isArray(item)) {
      result = result.concat(flattenWithLevels(item, level + 1));
    } else {
      result.push(`${item}-${level}`);
    }
  });
  return result;
}

// Test the function
let input = [[1, 2], [3, [4, [5, 6]]], 7];
console.log(flattenWithLevels(input)); // Output: ['1-1', '2-1', '3-1', '4-2', '5-3', '6-3', '7-0']

Question 3: Reconstructing the Nested Array

Input: ['1-1', '2-1', '3-1', '4-2', '5-3', '6-3', '7-0']
Output: [[1, 2], [3, [4, [5, 6]]], 7]

function reconstructNestedArray(arr) {
  let result = [];
  let stack = [{ array: result, level: -1 }];

  arr.forEach(item => {
    let [value, level] = item.split('-').map(Number);
    while (stack[stack.length - 1].level >= level) {
      stack.pop();
    }
    let currentArray = stack[stack.length - 1].array;
    let newArray = [];
    currentArray.push(level > stack[stack.length - 1].level ? newArray : value);
    if (level > stack[stack.length - 1].level) {
      stack.push({ array: newArray, level: level });
    }
  });

  return result;
}

// Test the function
let input = ['1-1', '2-1', '3-1', '4-2', '5-3', '6-3', '7-0'];
console.log(reconstructNestedArray(input)); // Output: [[1, 2], [3, [4, [5, 6]]], 7]

Final Thoughts

These questions test not only a candidate's ability to manipulate arrays but also their ability to think critically and adapt solutions as complexity increases. Candidates who solve these problems demonstrate a strong understanding of recursion, data structures, and logical problem-solving.

Happy coding and interviewing!

N
nikita1y ago

Great post! The Nippon India Small Cap Fund is an excellent choice for investors seeking high-growth opportunities. Its focus on small-cap stocks has delivered impressive results over time. The Nippon India Small Cap Fund NAV reflects consistent performance, making it appealing for long-term wealth creation. Additionally, the Nippon India Small Cap Fund portfolio is well-diversified, offering exposure to various promising sectors while managing risk effectively. It’s a fund worth considering for ambitious investors.

B

Great explanation of array flattening! The way you covered .flat() and its practical uses was super clear. I’ve always found flattening nested arrays to be one of those tasks that’s deceptively tricky at first but so satisfying once you get the hang of it. Have you ever tried using .reduce() for flattening as well? It’s an interesting alternative! I’ve been exploring similar JavaScript topics recently, and it’s always exciting to see content like this. Awesome work!

More from this blog

logicbricks

7 posts