Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-deal/1f6a3fff8a926dfb449abb2c8c179fcf to your computer and use it in GitHub Desktop.
Save a-deal/1f6a3fff8a926dfb449abb2c8c179fcf to your computer and use it in GitHub Desktop.
/*
Problem Description:
Given an array of integers AND/OR arbitrarily nested
arrays, return a single array of integers values only.
Input: <array>
Output: <array>
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Edge cases and Assumptions:
- Empty arrays should be ignored unless its the base array - in which case return early.
- Undefined elements should be ignored
- Mutation of original array should be avoided
Pseudo Solution (recursion):
If array is empty, return array => null case
Initialize array-to-return
Iterate through array
If element is a number, push into array-to-return
Else element is an array, recurse
for each element returned by the recursive call, push into base array
Return array-to-return
*/
const flattener = (toFlatten) => {
if (toFlatten.length === 0) return toFlatten;
let flattened = [];
for (const numOrArray of toFlatten) {
if (typeof numOrArray === 'number') flattened.push(numOrArray);
else {
for (const num of flattener(numOrArray)) {
flattened.push(num);
}
}
}
return flattened;
};
// Helper to ensure correctness
const assertsArraysEqual = (arr1, arr2) => {
if (arr1.length !== arr2.length) {
return `INCORRECT: Array lengths do not match: Array 1 = ${arr1.length} | Array 2 = ${arr2.length}`;
}
for (const [index, element] of arr1.entries()) {
if (element !== arr2[index]) {
return `INCORRECT: Array 1 at position ${index} with value ${element} does not match Array 2's ${arr2[index]} | ${arr1} !== ${arr2}`;
}
}
return `CORRECT: Array 1 and 2 match, flattening achieved!`;
};
/*
Sample Cases:
(Given Input) => (Expected Output)
[] => []
[1,2,3] => [1,2,3]
[1,[2],[[3]] => [1,2,3],
[[[4,5,6,],7],8],9] => [4,5,6,7,8,9]
[[[[[[[[[[[4]]]]]]]]]]] => [4]
*/
console.log(assertsArraysEqual(flattener([1,2,3]),[1,2,3]));
console.log(assertsArraysEqual(flattener([]),[]));
console.log(assertsArraysEqual(flattener([1,[2],[[3]]]),[1,2,3]));
console.log(assertsArraysEqual(flattener([[[[4,5,6],7],8],9]),[4,5,6,7,8,9]));
console.log(assertsArraysEqual(flattener([[[[[[[[[[[4]]]]]]]]]]]),[4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment