Skip to content

Commit 10672f1

Browse files
author
beck chen
committed
add more arrays and strings solutions
1 parent b8122f1 commit 10672f1

9 files changed

+318
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
** Print a 2D array in Diagonal ZigZag order
3+
** example:
4+
** 1 2 3 4
5+
** 5 6 7 8
6+
** 9 0 1 2
7+
** should turn into
8+
** 1 2 5 9 6 3 4 7 0 1 8
9+
*/
10+
11+
function zigZag(arr) {
12+
let rowIndex = 0, columnIndex = 0, isUp = true;
13+
14+
while (true) {
15+
// print first so we capture first point before our logic runs and updates coordinates
16+
console.log(arr[rowIndex][columnIndex]);
17+
18+
// if we reach top or bottom wall, AND we're not at right wall, go right.
19+
// note that this also captures bottom left corner case: in which we go right
20+
if (rowIndex === 0 || rowIndex === arr.length - 1 && columnIndex !== arr[0].length - 1) {
21+
columnIndex++;
22+
console.log(arr[rowIndex][columnIndex]);
23+
isUp = !isUp;
24+
} else if (columnIndex === 0 || columnIndex === arr[0].length - 1) {
25+
// otherwise, if we reach left or right wall, go down
26+
rowIndex++;
27+
console.log(arr[rowIndex][columnIndex]);
28+
isUp = !isUp;
29+
}
30+
31+
// if we're already at destination, exit the loop
32+
if (columnIndex === arr[0].length - 1 && rowIndex === arr.length - 1) {
33+
break;
34+
}
35+
36+
// we always go up right or down left
37+
columnIndex = isUp ? columnIndex + 1 : columnIndex - 1;
38+
rowIndex = isUp ? rowIndex - 1 : rowIndex + 1;
39+
}
40+
}
41+
42+
// this should print 1 2 5 9 6 3 4 7 0 1 8 2
43+
console.log(zigZag([[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2]]));
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Big Integer Addition
2+
// Given two arrays that represent numbers, find their sum
3+
// Example: 
4+
// a = [1, 6, 4, 3]
5+
// b = [1, 3, 1]
6+
7+
function bigIntegerAddition(arr1, arr2) {
8+
// figure out who's smaller and who's larger first
9+
const bigArr = arr1.length > arr2.length ? arr1 : arr2;
10+
let smallArr = arr1.length > arr2.length ? arr2 : arr1;
11+
12+
// since the two arrays could be of different sizes, we'd want to
13+
// padd the front of the smallerArr with zeros such that it becomes
14+
// the same size as the larger one
15+
smallArr = resizeWithZeros(smallArr, bigArr.length);
16+
17+
// we create a resultArr to store the sum of the two arrays.
18+
// note that it's only ever mathematicaly possible that resultArr be
19+
// at most one element longer than bigArr
20+
const resultArr = Array(bigArr.length + 1);
21+
let carry = 0;
22+
// we iterate backwards since that's how addition works
23+
for (let ii = bigArr.length - 1; ii >= 0; ii--) {
24+
const sum = smallArr[ii] + bigArr[ii];
25+
const smallestDigit = sum % 10 + carry;
26+
// assign smallestDigit to ii + 1 since resultArr is one element longer than bigArr
27+
resultArr[ii + 1] = smallestDigit;
28+
carry = Math.floor(sum / 10);
29+
}
30+
31+
return resultArr;
32+
}
33+
34+
function resizeWithZeros(arr, sizeToBecome) {
35+
// we'd like our smaller array to become a certain size
36+
// by padding the front of the array with zeros
37+
const resizedArr = Array(sizeToBecome).fill(0);
38+
let resizedArrBackwardsIndex = resizedArr.length - 1;
39+
let smallArrBackwardsIndex = arr.length - 1;
40+
41+
// we start assigning smaller array's element to resized array, backwards.
42+
// ex. smallArr = [1, 2], resizedArr = [0, 0, 0, 0], we start by assining element 1 of smallArr
43+
// to element 3 of resizedArr, and decrement these two indices at the same time, until
44+
// smallArr's index is 0. At this point resizedArr should be [0, 0, 1, 2]
45+
while (smallArrBackwardsIndex >= 0) {
46+
resizedArr[resizedArrBackwardsIndex] = arr[smallArrBackwardsIndex];
47+
resizedArrBackwardsIndex--;
48+
smallArrBackwardsIndex--;
49+
}
50+
51+
return resizedArr;
52+
}
53+
54+
console.log(bigIntegerAddition([3, 2, 4], [1, 9])); // should print 0, 3, 4, 3

sessions/array and strings/bigIntegerMultiplication.js

Whitespace-only changes.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Check if a string A is a rotation of another string B
2+
// For example, “atbobc” is a rotation of “bobcat”
3+
4+
function checkRotation(targetStr, refStr) {
5+
if (!targetStr || targetStr.length === 0 || !refStr || refStr.length === 0 || targetStr.length !== refStr.length) {
6+
return false;
7+
}
8+
9+
return (refStr + refStr).includes(targetStr);
10+
}
11+
12+
console.log(checkRotation('atbobc', 'bobcat'));
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Find the longest palindromic substring in a string
2+
// For example:
3+
// "abcababadef" => "ababa"
4+
// "ffabbahh" => “abba"
5+
6+
function longestPalindromicSubstring(fullStr) {
7+
if (!fullStr || fullStr.length === 0) { return null; }
8+
const fullCharsArr = fullStr.split('');
9+
let result = [];
10+
let currentMaxPalindromeLength = 0;
11+
12+
// handle odd length string
13+
for (let ii = 0; ii < fullCharsArr.length - 1; ii++) {
14+
// expand outwards from ii and check for palindrome
15+
let offset = 0;
16+
while (isValidIndex(ii - offset - 1, fullCharsArr)
17+
&& isValidIndex(ii + offset + 1, fullCharsArr)
18+
&& fullCharsArr[ii - offset - 1] === fullCharsArr[ii + offset + 1]) {
19+
offset++;
20+
}
21+
22+
const palindromeLengthAtIndex = 2 * offset + 1;
23+
if (palindromeLengthAtIndex > currentMaxPalindromeLength) {
24+
currentMaxPalindromeLength = palindromeLengthAtIndex;
25+
result = [ii - offset, ii + offset];
26+
}
27+
}
28+
29+
// handle even length string
30+
for (let ii = 0; ii < fullCharsArr.length - 1; ii++) {
31+
// expand outwards from ii and check for palindrome
32+
let offset = 0;
33+
while (isValidIndex(ii - offset, fullCharsArr)
34+
&& isValidIndex(ii + offset + 1, fullCharsArr)
35+
&& fullCharsArr[ii - offset] === fullCharsArr[ii + offset + 1]) {
36+
offset++;
37+
}
38+
39+
const palindromeLengthAtIndex = 2 * offset;
40+
if (palindromeLengthAtIndex > currentMaxPalindromeLength) {
41+
currentMaxPalindromeLength = palindromeLengthAtIndex;
42+
result = [ii - offset + 1, ii + offset];
43+
}
44+
}
45+
46+
return result;
47+
}
48+
49+
function isValidIndex(index, fullStr) {
50+
return index >= 0 && index < fullStr.length;
51+
}
52+
53+
// this should return [2, 6]
54+
console.log(longestPalindromicSubstring('abcivicyz'));
55+
// this should return [2, 5]
56+
console.log(longestPalindromicSubstring('xybaabop'));
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Print Elements of a Matrix in Spiral Order
2+
3+
function printElementsSpiralOrder(matrix) {
4+
if (!matrix || matrix.length === 0) { return; }
5+
6+
// note that this is NOT number of layers, but last layer index
7+
// picture a 2 x 3 matrix. In that case you would have 2 layers not 3,
8+
// with last layer index being 1
9+
const lastLayerIndex = Math.floor(matrix.length / 2);
10+
11+
// dont forget to include your lastLayerIndex in the loop
12+
for (let layerIndex = 0; layerIndex <= lastLayerIndex; layerIndex++) {
13+
printElementsInLayer(matrix, layerIndex);
14+
}
15+
}
16+
17+
function printElementsInLayer(matrix, layerIndex) {
18+
// for every spiral layer, we define the first and last columns and rows
19+
let firstColumn = layerIndex,
20+
lastColumn = matrix[0].length - 1 - layerIndex,
21+
firstRow = layerIndex,
22+
lastRow = matrix.length - 1 - layerIndex;
23+
24+
// print top
25+
// note that this does not include the rightmost element of the first row.
26+
// that element belongs to the right column
27+
for (let ii = firstColumn; ii < lastColumn; ii++) {
28+
console.log(matrix[firstRow][ii]);
29+
}
30+
31+
// print right wall
32+
// note that this does not include the bottom element of the right column.
33+
// that element belongs to the bottom
34+
for (let ii = firstRow; ii < lastRow; ii++) {
35+
console.log(matrix[ii][lastColumn]);
36+
}
37+
38+
// print bottom
39+
// note that this does not include the bottom element of the left column.
40+
// that element belongs to the left
41+
for (let ii = lastColumn; ii > firstColumn; ii--) {
42+
console.log(matrix[lastRow][ii]);
43+
}
44+
45+
// print left
46+
// note that this does not include the top element of the left column.
47+
// that element belongs to the top
48+
for (let ii = lastRow; ii > firstRow; ii--) {
49+
console.log(matrix[ii][firstColumn]);
50+
}
51+
}
52+
53+
// this should print 2, 3, 1, 6, 7, 9, 11, 4, 8, 12, 13, 5
54+
console.log(printElementsSpiralOrder([[2, 3, 1, 6], [12, 13, 5, 7], [8, 4, 11, 9]]));
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Reverse the order of the words in a string
2+
// For example: “what is your name” -> “name your is what”
3+
4+
function reverseOrderOfWords(wordsToReverse) {
5+
const wordsToReverseArr = wordsToReverse.split('');
6+
7+
// first we reverse the whole sentence
8+
reverseChars(wordsToReverseArr, 0, wordsToReverseArr.length - 1);
9+
10+
// loop from beginning of arr to second to last character,
11+
// look for start of string, and look for space, and
12+
// reverse the characters in between
13+
let wordStartIndex = 0;
14+
for (let ii = 0; ii < wordsToReverseArr.length - 1; ii++) {
15+
if (wordsToReverseArr[ii + 1] === ' ') {
16+
reverseChars(wordsToReverseArr, wordStartIndex, ii);
17+
wordStartIndex = ii + 2;
18+
}
19+
}
20+
21+
// reverse the last word
22+
reverseChars(wordsToReverseArr, wordStartIndex, wordsToReverseArr.length - 1);
23+
return wordsToReverseArr;
24+
}
25+
26+
function reverseChars(wordsToReverseArr, firstIndex, lastIndex) {
27+
while (firstIndex < lastIndex) {
28+
[wordsToReverseArr[firstIndex], wordsToReverseArr[lastIndex]]
29+
= [wordsToReverseArr[lastIndex], wordsToReverseArr[firstIndex]];
30+
firstIndex++;
31+
lastIndex--;
32+
}
33+
}
34+
35+
// should print "string a is this"
36+
console.log(reverseOrderOfWords('this is a string'));

sessions/array and strings/rotate2DArray.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,35 @@
33
// Also you need to rotate this in-place by modifying the original array,
44
// meaning you cannot create another 2D array to do this
55

6+
function rotateMatrix(matrix) {
7+
if (!matrix || matrix.length === 0 || matrix[0].length !== matrix.length) { return; }
8+
// we think of matrix in "layers" wrapping around the center
9+
// the main loop is to iterate from the outer layer to the innermost layer
10+
// (which is just the 1 center element)
11+
const numberOfLayers = Math.floor(matrix.length / 2);
12+
// iterate over the layers
13+
for (let layerIndex = 0; layerIndex < numberOfLayers; layerIndex++) {
14+
rotateLayerOfMatrix(matrix, layerIndex);
15+
}
16+
17+
return matrix;
18+
}
19+
20+
function rotateLayerOfMatrix(matrix, layerIndex) {
21+
const startIndex = layerIndex;
22+
const endIndex = matrix.length - 1 - layerIndex; // ex. for a 5 x 5 matrix, layer 1 ends at 5 - 1 - 1 = 3
23+
for (let ii = startIndex; ii < endIndex; ii++) {
24+
// store top element
25+
const storedTopElem = matrix[startIndex][startIndex + ii];
26+
// rotate left to top
27+
matrix[startIndex][startIndex + ii] = matrix[endIndex - ii][startIndex];
28+
// rotate bottom to left
29+
matrix[endIndex - ii][startIndex] = matrix[endIndex][endIndex - ii];
30+
// rotate right to bottom
31+
matrix[endIndex][endIndex - ii] = matrix[startIndex + ii][endIndex];
32+
// top to left
33+
matrix[startIndex + ii][endIndex] = storedTopElem;
34+
}
35+
}
36+
37+
console.log(rotateMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]));
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Rotate an array by X items
2+
// For example:
3+
// A = [1,2,3,4,5,6] and X = 2, Result = [5,6,1,2,3,4]
4+
// Note that X could be greater than the length of the array
5+
6+
/*
7+
** The logic here is:
8+
** 1. Get X % arr.length, in case X is longer than arr
9+
** 2. reverse the whole array
10+
** 3. reverse the first X items
11+
** 4. reverse the rest of the array
12+
*/
13+
function rotateArray(arr, x) {
14+
x = x % arr.length;
15+
reverseArr(arr, 0, arr.length - 1);
16+
reverseArr(arr, 0, x - 1);
17+
reverseArr(arr, x, arr.length - 1);
18+
19+
return arr;
20+
}
21+
22+
function reverseArr(arr, startIndex, endIndex) {
23+
while (startIndex < endIndex) {
24+
[arr[startIndex], arr[endIndex]] = [arr[endIndex], arr[startIndex]];
25+
startIndex++;
26+
endIndex--;
27+
}
28+
}
29+
30+
// should print [4, 5, 1, 2, 3]
31+
console.log(rotateArray([1, 2, 3, 4, 5], 2));

0 commit comments

Comments
 (0)