R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Spiral Traversing}

Problem

console.log(spiral(array));
//[0,1,2,3,4,9,14,19,18,17,16,15,10,5,6,7,8,13,12,11];

Note:  The subarrays in the input array are always of equal length.

var array = 
[[0,1,2,3,4], 
[5,6,7,8, 9], 
[10,11,12,13,14], 
[15,16,17,18,19]];
  1. Create a function that takes a multi-dimensional array of integer as input.
  2. From the top left, spiral traverse each element in a clockwise order.
  3. Return the spiral traversed integers in a single array.

One Approach

[[1,2,3,4], 
[5,6,7,8], 
[9,10,11,12], 
[13,14,15,16]]
  1. Loop through the arrays until there is no array.length
  2. Each loop
    • take and add the first row
    • take and add right items
    • reverse, take and add bottom row
    • take and add left items
[[10]]
[[5,6,7,8], 
[9,10,11,12], 
[13,14,15,16]]
[[5,6,7], 
[9,10,11], 
[13,14,15]]
[[5,6,7], 
[9,10,11], 
[15,14,13]]
[[5,6,7], 
[9,10,11]]
[[6,7], 
[10,11]]
[[10,11]]

Solution Code

function spiral(array) {

  let result = [];

  while (array.length) {
    // Steal the first row.
    result = result.concat(array.shift());
    // Steal the right items.
    for (var i = 0; i < array.length; i++) result.push(array[i].pop());
    // Steal the bottom row.
    result = result.concat((array.pop() || []).reverse());
    // Steal the left items.
    for (var i = array.length - 1; i >= 0; i--) result.push(array[i].shift());
  }

  return result;
}

One Recursive Approach

  1. Start with an empty array [ ]
  2. Base case: if the length of the array is 0 or 1, just return empty array or the one array
  3. If the length of the array is greater than 1, push the elements of the top row into the empty array.
  4. Transform the remaining elements so we can continue pushing the top row of elements into the empty array. Use recursion.
let array = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]];

[1,2,3,4]

[5,6,7,8],
[9,10,11,12],    
[13,14,15,16] ----> [8, 12, 16]
                    [7, 11, 15]
                    [6,10,14]
                    [5,9,13]                          [1,2,3,4,8,12,16]
                    (return first array and do the 
                    same thing with the remaining 
                    elements) ----------------------> [15,14,13]           [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
                                                      [11,10,9]
                                                      [7,6,5] -----------> [9,5]
                                                                           [10,6]
                                                                           [11,7] --> [6,7]
                                                                                      [10,11] --> [10,11]
                                                            

Solution

function spiral(array) {
    //if the array has a length of 0 or 1, return array
    if(!array.length) {
        return;
    } else if (array.length === 1) {
        return array[0]; //assuming multi-dim array
    }
    
    let firstRow = array[0],
        numRows = array.length,
        nextRows = [],
        newArr,
        rowIndex,
        colIndex = array[1].length - 1;
    
    //store elements in new arrays to push into the next row    
    for(colIndex; colIndex >= 0; colIndex--) {
        newArr = [];
        for(rowIndex = 1; rowIndex < numRows; rowIndex++) {
            newArr.push( array[rowIndex][colIndex]);
        }
        
        nextRows.push( newArr );
    }
    
    firstRow.push.apply( firstRow, spiral(nextRows));
    
    return firstRow;
}

Another Possible Solution (The Code)

function getSpiralElements(input) {
    var results = [ ];
    var limit = 20;
    function getSpiralHelper(multiDimArr) {
        if (multiDimArr.length === 1 || multiDimArr.length === 0) {
          if (multiDimArr[0] && multiDimArr[0].length) {
              results = results.concat(multiDimArr[0]);
          }
          return;
        }
        results = results.concat(multiDimArr.shift());
        multiDimArr.forEach(function(subArray) {
            results = results.concat(subArray.pop());
        });
        multiDimArr = multiDimArr.reverse();
        multiDimArr.forEach( function (el, index, arr) {
            arr[index] = el.reverse();
        });
        return getSpiralHelper(multiDimArr);
    }
    var valid = true;
    input.forEach(function (el) {
        if (el instanceof Array === false ) 
            valid = false;
    });
    if (!valid) throw new TypeError("Input should be an array of arrays!")
    getSpiralHelper(input);
    return results;
}

Conclusion  

REPL.IT (First Solution)

REPL.IT (Second Solution)

REPL.IT (Third Solution)

 Think about how to break up a problem into smaller pieces and just start tackling those smaller pieces.

Spiral Traversing

By Kate Humphrey

Spiral Traversing

Technical interview problem on generating string permutations

  • 947