[nb] Sync

This commit is contained in:
2022-02-20 21:55:27 -06:00
parent f9c2c88398
commit 3551467ef9
17 changed files with 38 additions and 0 deletions

View File

@@ -0,0 +1,139 @@
/*
*
* Given two binary search trees root1 and root2.
* Return a list containing all the integers from both trees sorted in ascending order.
*
*
* Example 1:
* Input: root1 = [2,1,4], root2 = [1,0,3]
* Output: [0,1,1,2,3,4]
*
* Example 2:
* Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
* Output: [-10,0,0,1,2,5,7,10]
*
* Example 3:
* Input: root1 = [], root2 = [5,1,7,0,2]
* Output: [0,1,2,5,7]
*
* Example 4:
* Input: root1 = [0,-10,10], root2 = []
* Output: [-10,0,10]
*
* Example 5:
* Input: root1 = [1,null,8], root2 = [8,1]
* Output: [1,1,8,8]
*
* Constraints:
* Each tree has at most 5000 nodes.
* Each node's value is between [-10^5, 10^5].
*
*/
const { assert } = require('../../util/js');
/**
* Definition for a binary tree node.
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {number[]}
*/
const getAllElements = function(root1, root2) {
const convertToList = (node, list) => {
if(!node) {
return;
}
convertToList(node.left, list);
list.push(node.val);
convertToList(node.right, list);
}
let listA = [];
let listB = [];
const result = [];
convertToList(root1, listA);
convertToList(root2, listB);
let i = 0;
let j = 0;
while(i < listA.length && j < listB.length) {
if (listA[i] < listB[j]) {
result.push(listA[i]);
i++;
} else {
result.push(listB[j]);
j++;
}
}
while(i < listA.length) {
result.push(listA[i]);
i++;
}
while(j < listB.length){
result.push(listB[j]);
j++;
}
return result;
};
/* Test Case 1
* Input: root1 = [2,1,4], root2 = [1,0,3]
* Output: [0,1,1,2,3,4]
*/
root1 = new TreeNode(2);
root1.left = new TreeNode(1);
root1.right = new TreeNode(4);
root2 = new TreeNode(1);
root2.left = new TreeNode(0);
root2.right = new TreeNode(3);
sol = [0,1,1,2,3,4];
assert(JSON.stringify(getAllElements(root1,root2)) === JSON.stringify(sol), 'Output: [0,1,1,2,3,4]');
/* Test Case 2
* Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
* Output: [-10,0,0,1,2,5,7,10]
*/
root1 = new TreeNode(0);
root1.left = new TreeNode(-10);
root1.right = new TreeNode(10);
root2 = new TreeNode(5);
root2.left = new TreeNode(1);
root2.right = new TreeNode(7);
root2.left.left = new TreeNode(0);
root2.left.right = new TreeNode(2);
sol = [-10,0,0,1,2,5,7,10];
assert(JSON.stringify(getAllElements(root1, root2)) === JSON.stringify(sol), 'Output: [-10,0,0,1,2,5,7,10]');
/* Test Case 3
* Input: root1 = [], root2 = [5,1,7,0,2]
* Output: [0,1,2,5,7]
*/
root1 = undefined;
root2 = new TreeNode(5);
root2.left = new TreeNode(1);
root2.right = new TreeNode(7);
root2.left.left = new TreeNode(0);
root2.left.right = new TreeNode(2);
sol = [0,1,2,5,7];
assert(JSON.stringify(getAllElements(root1,root2)) === JSON.stringify(sol), 'Output: [0,1,2,5,7]');
/* Test Case 4
* Input: root1 = [0,-10,10], root2 = []
* Output: [-10,0,10]
*/
root1 = new TreeNode(0);
root1.left = new TreeNode(-10);
root1.right = new TreeNode(10);
root2 = undefined;
sol = [-10,0,10];
assert(JSON.stringify(getAllElements(root1, root2)) === JSON.stringify(sol), 'Output: [-10,0,10]');

View File

@@ -0,0 +1,2 @@
5-longest-palindromic-substring
22-generate-parenthesis

View File

@@ -0,0 +1,53 @@
package main
import (
"strings"
"container/list"
)
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
()()(); (())(); ((()));
()(());
(()())
Input: n = 1
Output: ["()"]
()(); (())
Constraints:
1 <= n <= 8
*/
func rec(input []string, left int, right int, n int, ans *[]string) {
if len(input) == 2*n {
*ans = append(*ans, strings.Join(input, ""))
return
}
if left < n {
input = append(input, "(")
rec(input, left+1, right, n, ans)
input = input[0:len(input)-1]
}
if right < left {
input = append(input, ")")
rec(input, left, right+1, n, ans)
input = input[0:len(input)-1]
}
}
func generateParenthesis(n int) []string {
var output = make([]string, 2*n)
var input = make([]string, 2*n)
rec(input, 0, 0, n, &output)
return output
}
func main() {
generateParenthesis(3)
}

View File

@@ -0,0 +1,30 @@
function generateParenthesis(n) {
const output = []
const rec = (input = [], left = 0, right = 0) => {
if (input.length === 2*n) {
output.push(input.join(''));
console.log('sol');
return
}
if (left < n) {
input.push('(');
console.log(input.join('') + ' l=' + left + ' r=' + right)
rec(input, left+1, right);
console.log('back left');
input.pop();
}
if (right < left) {
input.push(')');
console.log(input.join('') + ' l=' + left + ' r=' + right)
rec(input, left, right+1);
console.log('back right l=' + left);
input.pop();
console.log(input.join('') + ' l=' + left + ' r=' + right)
}
};
rec();
return output;
}
console.log(generateParenthesis(3));

View File

@@ -0,0 +1,25 @@
from typing import List
# ()()()
# (())()
# ((()))
# ()(())
# (()())
def generateParenthesis(n: int) -> List[str]:
ans = []
def backtrack(S = [], left = 0, right = 0):
if len(S) == 2 * n:
ans.append("".join(S))
return
if left < n:
S.append("(")
backtrack(S, left+1, right)
S.pop()
if right < left:
S.append(")")
backtrack(S, left, right+1)
S.pop()
backtrack()
return ans
generateParenthesis(3)

View File

@@ -0,0 +1,102 @@
package main
import (
"fmt"
"strings"
)
/*
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
 
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters.
*/
/*
Hints: If the string is 2 characters and they are both the same character then it is a palindrome (ie: aa or 11)
So you can use create a table to calculate a table where if table[i+1][j-1] is true and string[i+1] == string[j-1]
then the substring string is a palindrome
You can see that i+1, j-1 is like two pointers with one going forward and the other going backwards
a b a
a 0 0 1
b 0 1 0
a 1 0 1
*/
func longestPalindrome(s string) string {
/*
If string s has a len = 1 then the longest palindrome is s
If string s has len = 2 and the two characters are the same then the longest palindrome is s
*/
var n = len(s)
if n == 1 {
return s
}
if n == 2 && s[0] == s[1] {
return s
}
// Generate memory table table[i][i] = true
var output string
dp := make([][]bool, n)
for i:= 0; i < n - 1; i++ {
dp[i] = make([]bool, n)
dp[i][i] = true
}
// Need to do this to access by index
// see https://stackoverflow.com/questions/15018545/how-to-index-characters-in-a-golang-string
strarr := strings.Split(s, "")
// Also check for palidrome where length == 2 using s[i] == s[i+1]
for i := 0; i < n - 1; i++ {
if (strarr[i] == strarr[i+1]) {
dp[i][i+1] = true
output = s[i:i+1]
}
}
// n = 5
// i = 2; x = 0; y = 1
// Find substring where n > 2
for i := 2; i < n - 1; i++ {
for x := 0; x < n - i; x++ {
// starting at x find the end idx (len substring - 1 )
y := x + i - 1
if (dp[x+1][y-1] && strarr[x] == strarr[y]) {
output = s[x:(y+1)]
}
}
}
return output
}
func main () {
fmt.Println(longestPalindrome("babad"))
}

View File

@@ -0,0 +1,47 @@
/*
* Given an array of strings, group anagrams together.
*
* Example:
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Output: [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*
* Note:
* All inputs will be in lowercase.
* The order of your output does not matter.
*
*/
const { assert } = require('../../util/js');
/**
* @param {string[]} strs
* @return {string[][]}
*/
const groupAnagrams = (strs) => {
const map = {};
strs.forEach(str => {
const key = str.split('').sort().join('');
if (!map[key]) {
map[key] = [str];
} else {
map[key].push(str);
}
});
return Object.values(map);
};
/* Test Case 1
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Output: [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*/
x = [ 'eat', 'tea', 'tan', 'ate', 'nat', 'bat'];
sol = [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']];
assert(JSON.stringify(groupAnagrams(x)) === JSON.stringify(sol), `Output: ${JSON.stringify(sol)}`);

View File

@@ -0,0 +1,115 @@
/*
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
*/
const { assert } = require('../../util/js');
/**
* @param {number} num
* @return {string}
*/
const intToRoman = function(num) {
const romanMap = {
"1": "I",
"4": "IV",
"5": "V",
"9": "IX",
"10": "X",
"40": "XL",
"50": "L",
"90": "XC",
"100": "C",
"400": "CD",
"500": "D",
"900": "CM",
"1000": "M"
};
const numberOfDigits = Number(num).toString().length;
const pows = [];
// Create an array representing the powers of 10s of the number
let remaining = num;
for (let i = 0; i < numberOfDigits; i++){
let digit = (remaining / (Math.pow(10, i))) % 10;
remaining = remaining - (Math.pow(10, i) *digit);
pows.unshift(Math.pow(10,i)*digit);
}
const result = [];
const counters = [9, 5, 4, 1];
// Check hash map if it doesn't exist subtract the largest valid roman numeral and save valid numeral
pows.forEach(pow => {
if (romanMap[pow]){
result.push(romanMap[pow]);
} else {
let rem = pow;
while(rem) {
const numberOfDigits = Number(rem).toString().length;
counters.forEach(counter => {
const key = counter * Math.pow(10, numberOfDigits-1);
if (key <= rem) {
rem = rem - key;
result.push(romanMap[key]);
}
});
}
}
})
return result.join('');
};
/* Test Case 1
* Input: 3
* Output: "III"
*/
x = 3;
sol = 'III';
assert(intToRoman(x) === sol, 'Output: III');
/* Test Case 2
* Input: 4
* Output: IV
*/
x = 4;
sol = 'IV';
assert(intToRoman(x) === sol, 'Output: IV');
/* Test Case 3
* Input: 9
* Output: 'IX'
*/
x = 9;
sol = 'IX';
assert(intToRoman(x) == sol, 'Output: IX');
/* Test Case 4
* Input: 58
* Output: 'LVIII'
*/
x = 58;
sol = 'LVIII';
assert(intToRoman(x) == sol, 'Output: LVIII');
/* Test Case 5
* Input: 1994
* Output: 'MCMXCIV'
*/
x = 1994;
sol = 'MCMXCIV';
assert(intToRoman(x) == sol, 'Output: MCMXCIV');

View File

@@ -0,0 +1,58 @@
/*
* Given a collection of distinct integers, return all possible permutations.
* Example:
*
* Input: [1,2,3]
* Output:
*
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
*
* ]
*/
const { assert } = require('../../util/js');
/**
* @param {number[]} nums
* @return {number[][]}
*/
const permute = function(nums) {
const permuRecursive = (soFar, rest, perm) => {
if (rest.length === 0) {
perm.push(soFar);
}
for(let i = 0; i < rest.length; i++) {
const rem = [...rest.slice(0, i), ...rest.slice(i+1)];
permuRecursive([...soFar, rest[i]], rem, perm);
}
}
const result = [];
permuRecursive([], nums, result);
return result;
};
/* Test Case 1
* Input: [1,2,3]
* Output:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
*
* ]
*/
x = [1,2,3];
sol = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]];
assert(JSON.stringify(permute(x)) === JSON.stringify(sol), `Output: ${JSON.stringify(sol)}`);

View File

@@ -0,0 +1,96 @@
/*
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [231, 231 1]
*/
const { assert } = require('../../util/js');
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
const isNeg = n < 0 ? true: false;
if (n === 0) {
return 1;
}
if (n === 1) {
return x;
}
if (n === -1) {
return 1/x;
}
const storedCalcs = {};
const recursivePow = (x, n) => {
if (n === 2) {
return isNeg ? (1/x * 1/x) : x * x;
}
if (n === 1) {
return isNeg ? 1/x : x;
}
if (n === 0) {
return 1;
}
const firstHalf = Math.floor(parseInt(Math.abs(n) / 2));
const secondHalf = Math.abs(n) - firstHalf;
if(storedCalcs[n]) {
return storedCalcs[n];
}
const result = recursivePow(x, firstHalf) * recursivePow(x, secondHalf);
storedCalcs[n] = result;
return result;
};
return recursivePow(x, n);
}
/* Test Case 1
* Input: 2.00000, 10
* Output: 1024.00000
*/
x = 2.00000;
n = 10;
sol = 1024.00000;
assert(myPow(x, n) == sol, 'Output: 1024.00000');
/* Test Case 2
* Input: 2.10000, 3
* Output: 9.261
*/
x = 2.10000;
n = 3;
sol = 9.261;
assert(myPow(x, n).toFixed(3) == sol, 'Output: 9.261');
/* Test Case 3
* Input: 2.00000, -2
* Output: 0.25
*/
x = 2.00000;
n = -2;
sol = 0.25;
assert(myPow(x, n) == sol, 'Output: 0.25000');

View File

@@ -0,0 +1,18 @@
const RecPermute = (soFar, rest) => {
if (rest.length === 0) {
console.log('result', soFar);
console.log('\n\n');
} else {
for (let i = 0; i < rest.length; i++) {
const remaining = rest.substring(0,i) + rest.substring(i+1);
console.log('r', remaining)
console.log('R', rest);
console.log('SF', soFar);
console.log('------');
RecPermute(soFar + rest[i], remaining);
}
}
};
x = 'abc';
RecPermute('', x);

View File

@@ -0,0 +1,62 @@
/*
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [231, 231 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
*/
const { assert } = require('../../util/js');
/**
* @param {number} x
* @return {number}
*/
const reverse = function(x) {
const MAX_INT = Math.pow(2,31) -1;
const MIN_INT = Math.pow(2,31)* -1;
const X = x.toString();
const isNeg = X[0] === '-';
let reverseIntegerString = X.split('').reverse().join('');
const reverseInteger = isNeg ? parseInt(reverseIntegerString) * -1 : parseInt(reverseIntegerString);
return (reverseInteger >= MAX_INT || reverseInteger <= MIN_INT) ? 0 : reverseInteger;
};
/* Test Case 1
* Input: 123
* Output: 321
*/
x = 123;
sol = 321;
assert(reverse(x) === sol, 'Output: 321');
/* Test Case 2
* Input: -123
* Output: -321
*/
x = -123;
sol = -321
assert(reverse(x) === sol, 'Output: -321');
/* Test Case 3
* Input: 120
* Output: 21
*/
x = 120;
sol = 21;
assert(reverse(x) == sol, 'Output: 21');

View File

@@ -0,0 +1,92 @@
/*
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
*/
const { assert } = require('../../util/js');
/* @param {string} s
* @return {number}
*/
const romanToInt = function(s) {
const romanMap = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
};
let result = 0;
let i = 0;
while (i < s.length) {
const currentRomanValue = romanMap[s[i]];
const nextRomanValue = romanMap[s[i+1]];
if (nextRomanValue > currentRomanValue) {
result += (nextRomanValue - currentRomanValue)
i+=2;
} else {
result += currentRomanValue;
i++;
}
}
return result;
};
/* Test Case 1
* Input: 3
* Output: "III"
*/
x = 'III';
sol = 3;
assert(romanToInt(x) === sol, 'Output: 3');
/* Test Case 2
* Input: IV
* Output: 4
*/
x = 'IV';
sol = 4;
assert(romanToInt(x) === sol, 'Output: 4');
/* Test Case 3
* Input: 'IX'
* Output: 9
*/
x = 'IX';
sol = 9;
assert(romanToInt(x) == sol, 'Output: 9');
/* Test Case 4
* Input: 'LVIII'
* Output: 58
*/
sol = 58;
x = 'LVIII';
assert(romanToInt(x) == sol, 'Output: 58');
/* Test Case 5
* Input: 'MCMXCIV'
* Output: 1994
*/
x = 'MCMXCIV';
sol = 1994;
assert(romanToInt(x) == sol, 'Output: 1994');

View File

@@ -0,0 +1,146 @@
/*
* Implement atoi which converts a string to an integer.
*
* The function first discards as many whitespace characters as necessary until the first non-whitespace character is found.
* Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible,
* and interprets them as a numerical value.
*
* The string can contain additional characters after those that form the integral number, which are ignored and have no effect
* on the behavior of this function.
*
* If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because
* either str is empty or it contains only whitespace characters, no conversion is performed.
* If no valid conversion could be performed, a zero value is returned.
*
* Note:
* Only the space character ' ' is considered as whitespace character.
* Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [231, 231 1]. If the numerical value is out of the range of representable values, INT_MAX (231 1) or INT_MIN (231) is returned.
*/
const { assert } = require('../../util/js');
/**
* @param {string} str
* @return {number}
*/
const myAtoi = function(str) {
const INT_MAX = Math.pow(2,31) -1;
const INT_MIN = Math.pow(2,31)* -1;
let trimmedStr = str.trim();
const valid = ['0', '1', '2','3','4','5','6','7','8','9', '-', '+'];
const signs = ['-', '+'];
if(
!valid.includes(trimmedStr[0])
|| (trimmedStr.length === 1&& signs.includes(trimmedStr[0]))
|| (signs.includes(trimmedStr[0]) && signs.includes(trimmedStr[1]))
|| (signs.includes(trimmedStr[0]) && !valid.includes(trimmedStr[1]))
) {
return 0;
}
const decimalIndx = str.indexOf('.');
if (decimalIndx > -1){
trimmedStr = str.substring(0, decimalIndx);
}
const isNeg = trimmedStr[0] === '-';
const isPlus = trimmedStr[0] === '+';
const queue = [];
const list = trimmedStr.split('');
for(let i = 0; i < list.length; i++){
const char = list[i];
if(!valid.includes(char) ||(signs.includes(char) && i > 0)) {
break;
}
if(valid.includes(char)){
queue.push(char);
}
}
if(isNeg){
queue.shift();
}
if (isPlus){
queue.shift();
}
let integer = parseInt(queue.pop(), 10);
while(queue.length){
let multipler = queue.length;
let char = queue.shift();
integer += (Math.pow(10, multipler)* parseInt(char, 10));
}
if(isNeg){
integer= integer*-1;
}
if (integer >INT_MAX){
return INT_MAX;
}
if (integer < INT_MIN){
return INT_MIN;
}
return integer;
};
/*
* Test Case 1
* Input: "42"
* Output: 42
*/
x = '42';
sol = 42;
assert(myAtoi(x) === sol, 'Output: 42');
/* Explanation: The first non-whitespace character is '-', which is the minus sign.
* Then take as many numerical digits as possible, which gets 42.
*/
/* Test Case 2
* Input: " -42"
* Output: -42
*/
x = " -42";
sol = -42;
assert(myAtoi(x) === sol, 'Output: -42');
/* Test Case 3
* Input: "4193 with words"
* Output: 4193
*/
x = '4193 with words';
sol = 4193;
assert(myAtoi(x) === sol, 'Output: 4193');
/* Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
*/
/* Test Case 4
* Input: "words and 987"
* Output: 0
*/
x = 'words and 987';
sol = 0;
assert(myAtoi(x) === sol, 'Output: 0');
/* Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign.
* Therefore no valid conversion could be performed.
*/
/* Test Case 5
* Input: "-91283472332"
* Output: -2147483648
*/
x = '-91283472332';
sol = -2147483648;
assert(myAtoi(x) === sol, 'Output: -2147483648');
/*Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
* Thefore INT_MIN (231) is returned.
*/

View File

@@ -0,0 +1,8 @@
module.exports.assert = (condition, message) => {
if(condition) {
console.log(`${message}`);
}
else {
console.error(`${message}`);
}
}

View File

@@ -0,0 +1,118 @@
/*
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
*/
const { assert } = require('../../util/js');
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
const convert = (s, numRows) => {
const pattern = [];
let x = 0;
let y = 0;
let goingDown = true;
for(let i = 0; i < s.length; i++){
if (y === numRows && goingDown) {
y = numRows - 2;
x++;
goingDown = false;
}
if (y == -1 && !goingDown){
y = 1;
x++;
goingDown = true;
}
if (!pattern[x]){
pattern[x] = [];
}
pattern[x][y] = s[i];
if (goingDown){
y++;
} else {
y--;
}
}
let col = 0;
let output='';
let j = 0;
// Time complexity: O(n)
while (j < s.length) {
// Reset col counter to 0 if at the last col
if (col === pattern.length) {
col = 0;
}
// Remove empty cols from list then skip
if (!pattern[col] || pattern[col].length === 0){
pattern.splice(col, 1);
continue;
}
const char = pattern[col][0];
// Add character to output and increment char counter
// Don't increment if character is null
// char can be null since we were not adding elements in every index
if (char) {
output+=char;
j++;
}
pattern[col].shift();
col++;
}
return output;
};
let s, numRows;
/* Test Case 1
* Input s = "PAYPALISHIRING", numRows = 3
* Output: "PAHNAPLSIIGYIR"
*/
s = 'PAYPALISHIRING';
numRows = 3;
sol = 'PAHNAPLSIIGYIR';
assert(convert(s, numRows) == sol, 'Output: "PAHNAPLSIIGYIR"');
/* Test Case 2
* Input: s = "PAYPALISHIRING", numRows = 4
* Output: "PINALSIGYAHRPI"
*/
s = 'PAYPALISHIRING';
numRows = 4;
sol = 'PINALSIGYAHRPI';
assert(convert(s, numRows) == sol, 'Output: "PINALSIGYAHRPI"');
/* Test Case 3
* Input: s = "AB", numRows = 1
* Output: "AB"
*/
s = 'AB';
numRows = 1;
sol = 'AB';
assert(convert(s, numRows) == sol, 'Output: "AB"');