* }
* }
* }
* }
**/
================================================
FILE: coding_interviews/interviews/smartnews/countries.js
================================================
function solution(A) {
let countries = buildCountriesMapper(A);
let countriesCount = 0;
for (let row = 0; row < A.length; row++) {
for (let col = 0; col < A[row].length; col++) {
const country = A[row][col];
if (!countries[row][col]) countriesCount++;
verifyCountry(A, country, row, col, countries);
}
}
return countriesCount;
}
function buildCountriesMapper(A) {
const mapper = [];
for (let row = 0; row < A.length; row++) {
const line = [];
for (let col = 0; col < A[row].length; col++) {
line.push(false);
}
mapper.push(line);
}
return mapper;
}
function verifyCountry(A, country, row, col, countries) {
if (
row < 0 ||
col < 0 ||
row >= A.length ||
col >= A[row].length ||
countries[row][col] ||
country !== A[row][col]
)
return;
countries[row][col] = true;
country = A[row][col];
verifyCountry(A, country, row, col - 1, countries);
verifyCountry(A, country, row, col + 1, countries);
verifyCountry(A, country, row + 1, col, countries);
}
================================================
FILE: coding_interviews/interviews/smartnews/emiter.js
================================================
/*
Event Emiter
1. `on` & `emit`
2. `off`
3. `once`
*/
class EventEmiter {
events = {};
on(eventName, fn) {
if (!this.events[eventName]) {
this.events[eventName] = [{ subscriber: 'on', fn }];
} else {
this.events[eventName].push({ subscriber: 'on', fn });
}
}
emit(eventName, ...args) {
if (this.events[eventName]) {
for (let i = 0; i < this.events[eventName].length; i++) {
this.events[eventName][i].fn(...args);
if (this.events[eventName][i].subscriber === 'once') {
this.off(eventName, this.events[eventName][i].fn);
}
}
}
}
off(eventName, fn) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter(
(event) => event.fn !== fn
);
}
}
once(eventName, fn) {
if (!this.events[eventName]) {
this.events[eventName] = [{ subscriber: 'once', fn }];
} else {
this.events[eventName].push({ subscriber: 'once', fn });
}
}
}
const eventEmitet = new EventEmiter();
const fn1 = (param1, param2) => console.log('test 1', param1, param2);
eventEmitet.once('test', fn1);
eventEmitet.emit('test', 'param1', 'param2'); // log param1, param2
eventEmitet.emit('test', 'param1', 'param2'); // log nothing
================================================
FILE: coding_interviews/interviews/smartnews/getTriplets.js
================================================
// /**
// * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// *
// * Note:
// * The solution set must not contain duplicate triplets.
// *
// * Example:
// * Given array nums = [-1, 0, 1, 2, -1, -4],
// *
// * A solution set is:
// * [
// * [-1, 0, 1],
// * [-1, -1, 2]
// * ]
// */
const getTriplets = (nums) => {
const triplets = [];
const tripletMapper = {};
const allNumbers = {};
nums.forEach((num) => (allNumbers[num] = true));
for (let i = 0; i < nums.length - 2; i++) {
for (let j = i + 1; j < nums.length - 1; j++) {
const firstTwoSum = nums[i] + nums[j];
const targetNumber = 0 - firstTwoSum;
if (allNumbers[targetNumber]) {
const mapperKey = stringify([nums[i], nums[j], targetNumber]);
if (!tripletMapper[mapperKey]) {
tripletMapper[mapperKey] = true;
triplets.push([nums[i], nums[j], targetNumber]);
}
}
}
}
return triplets;
};
const stringify = (nums) => nums[0] + '.' + nums[1] + '.' + nums[2];
console.log(getTriplets([0, 0, 0]));
console.log(getTriplets([-1, 0, 1, 2, -1, -4]));
console.log(getTriplets([0, -1, 2]));
console.log(getTriplets([0, -1, Infinity]));
================================================
FILE: coding_interviews/interviews/uber/longest-words.js
================================================
// console.log('Hello world');
// I would like you to write a function which takes two arguments: a list of words, each separated by comma, and a list of letters. The function should output the longest words from which can be made using the letters in the list.
// ---------
// Inputs
// ---------
// Words: aab,cab,abba,abacus,scabs,scab,bacca,ab
// Letters: aabbscb
// aab, cab, abba
// ----------------------
// Expected Output
// ----------------------
// abba, scab
// Algorithm Analysis
// O(L + W * CW) => O(W * CW)
// L = letters
// W = words
// CW = chars of word
function buildCounter(letters) {
let lettersCounter = {};
for (let char of letters) {
if (lettersCounter[char]) {
lettersCounter[char]++;
} else {
lettersCounter[char] = 1;
}
}
return lettersCounter;
}
function getLongestWords(words, letters) {
let lettersCounter = buildCounter(letters);
let longestLength = 0;
let allValidWords = {};
for (let word of words) {
let lettersCounterCopy = { ...lettersCounter }; // O(L)
let isValid = true;
for (let char of word) {
if (
lettersCounterCopy[char] == undefined ||
lettersCounterCopy[char] === 0
) {
isValid = false;
break;
}
lettersCounterCopy[char] -= 1;
}
if (isValid) {
if (allValidWords[word.length]) {
allValidWords[word.length].push(word);
} else {
allValidWords[word.length] = [word];
}
longestLength = Math.max(longestLength, word.length);
}
}
return allValidWords[longestLength] || [];
}
console.log(
getLongestWords(
['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],
'aabbscb'
)
);
console.log(
getLongestWords(
['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],
''
)
);
console.log(
getLongestWords(
['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],
'aabbscbsu'
)
);
console.log(
getLongestWords(
['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'],
'aabbscbs'
)
);
console.log(getLongestWords([''], 'batata'));
console.log(getLongestWords(['batata'], 'batata'));
console.log(getLongestWords(['aaaaaaaaaaaaaa'], 'aaaaaaaaaaaaaa'));
================================================
FILE: coding_interviews/interviews/uber/maxFrequency.js
================================================
export function maxFrequency(numbers) {
let maxFrequencyNumber = -1;
let result = -1;
let numberToFrequencyMap = {};
for (let num of numbers) {
if (numberToFrequencyMap[num]) {
numberToFrequencyMap[num]++;
} else {
numberToFrequencyMap[num] = 1;
}
}
Object.entries(numberToFrequencyMap).forEach(([num, frequency]) => {
if (frequency > maxFrequencyNumber) {
maxFrequencyNumber = frequency;
result = Number(num);
}
});
return result;
}
================================================
FILE: coding_interviews/interviews/uber/permutations.js
================================================
/*
Input [2,3]
Output: ["AD", "BD", "CD", "AE", "BE", "CE", "AF", "BF", "CF"], 9
Input []
Output: [], 0
Input [1,2]
Output: ["A", "B", "C"], 3
Input [0,2]
Output: ["+A", "+B", "+C"], 3
Input [2,3,4]
Output: ["ADG", "ADH", "ADI", "AEG", ...]
*/
let numberToValues = {
0: '+',
1: ' ',
2: 'ABC',
3: 'DEF',
4: 'GHI',
5: 'JKL',
6: 'MNO',
7: 'PQRS',
8: 'TUV',
9: 'WXYZ',
};
function combine(permutations, chars) {
let combination = [];
for (let permutation of permutations) {
for (let char of chars) {
combination.push(permutation + char);
}
}
return combination;
}
function permutations(numbers) {
if (numbers.length === 0) {
return [];
}
let allPermutations = [];
let num = numbers[0];
let chars = numberToValues[num];
for (let char of chars) {
allPermutations.push(char);
}
for (let index = 1; index < numbers.length; index++) {
let num = numbers[index];
let chars = numberToValues[num];
allPermutations = combine(allPermutations, chars);
}
return allPermutations;
}
console.log(permutations([2, 3]));
console.log(permutations([2, 3, 4]));
console.log(permutations([1, 2, 3, 4]));
console.log(permutations([0, 1, 2, 3, 4]));
================================================
FILE: coding_interviews/interviews/uber/tests/maxFrequency.test.js
================================================
import { describe, expect, it } from 'vitest';
import { maxFrequency } from '../maxFrequency';
describe('maxFrequency', () => {
it('', () => {
expect(maxFrequency([2, 2, 2, 3, 3, 1])).toEqual(2);
});
it('', () => {
expect(maxFrequency([1, 1, 2, 2, 3, 3])).toEqual(1);
});
it('', () => {
expect(maxFrequency([])).toEqual(-1);
});
});
================================================
FILE: coding_interviews/javascript/array/binary-search.js
================================================
function getMiddle(start, end) {
return Math.floor((start + end) / 2);
}
function binarySearch(numbers, target) {
let start = 0;
let end = numbers.length - 1;
let middle = getMiddle(start, end);
let found = false;
while (start <= end && !found) {
middle = getMiddle(start, end);
const middleNumber = numbers[middle];
if (middleNumber === target) found = true;
if (middleNumber > target) end = middle - 1;
if (middleNumber < target) start = middle + 1;
}
return found;
}
function logResult(list, target) {
console.log(binarySearch(list, target));
}
logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5); // true
logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11); // false
logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], -1); // false
logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0); // false
logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9); // true
logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1); // true
================================================
FILE: coding_interviews/javascript/array/slice.js
================================================
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
list.slice(0); // all elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list.slice(0, 3); // first 3 elements: [1, 2, 3]
list.slice(1, 4); // from 2 to 4: [2, 3, 4]
================================================
FILE: coding_interviews/javascript/array/subarrays.js
================================================
function generateSubarrays(arr, start, end, result) {
if (end == arr.length) return;
else if (start > end) generateSubarrays(arr, 0, end + 1, result);
else {
result.push(arr.slice(start, end + 1));
generateSubarrays(arr, start + 1, end, result);
}
}
let arr = [1, 2, 3];
let result = [];
generateSubarrays(arr, 0, 0, result);
console.log(result);
================================================
FILE: coding_interviews/javascript/hashmap/iteration.js
================================================
let hashmap = {};
let numbers = [1, 2, 3, 4, 5, 1, 6, 1, 7, 0, 8, 9, 10, 0, 1];
for (let number of numbers) {
if (hashmap[number]) {
hashmap[number]++;
} else {
hashmap[number] = 1;
}
}
// if I need keys and values
Object.entries(hashmap).forEach(([key, value]) => {
console.log(`${key} -> ${value}`);
});
// if I need keys only
Object.keys(hashmap).forEach((key) => {
console.log(key);
});
// if I need values only
Object.values(hashmap).forEach((value) => {
console.log(value);
});
================================================
FILE: coding_interviews/javascript/hashmap/object.js
================================================
// building a hashmap to count numbers
let hashmap = {};
let numbers = [1, 2, 3, 4, 5, 1, 6, 1, 7, 0, 8, 9, 10, 0, 1];
for (let number of numbers) {
if (hashmap[number]) {
hashmap[number]++;
} else {
hashmap[number] = 1;
}
}
console.log(hashmap);
================================================
FILE: coding_interviews/javascript/queue/queue.js
================================================
let queue = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function push(queue, value) {
queue.push(value);
}
function pop(queue) {
return queue.shift();
}
function front(queue) {
return queue[0];
}
function isEmpty(queue) {
return queue.length === 0;
}
console.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
push(queue, 0);
console.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0]
pop(queue); // 1
console.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
front(queue); // 2
isEmpty(queue); // false
while (!isEmpty(queue)) {
queue.pop();
}
isEmpty(queue); // true
console.log(queue);
================================================
FILE: coding_interviews/javascript/stack/stack.js
================================================
let stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function push(stack, value) {
stack.push(value);
}
function pop(stack) {
return stack.pop();
}
function top(stack) {
return stack[stack.length - 1];
}
function isEmpty(stack) {
return stack.length === 0;
}
console.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
push(stack, 11);
console.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
pop(stack); // 11
console.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
top(stack); // 10
isEmpty(stack); // false
while (!isEmpty(stack)) {
stack.pop();
}
isEmpty(stack); // true
console.log(stack);
================================================
FILE: coding_interviews/javascript/string/alphabet.js
================================================
// index to alphabet char
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
alphabet[0]; // a
alphabet[1]; // b
// -------------------- // --------------------
// alphabet char to index
function getIndexFromChar(char) {
return char.charCodeAt() - 97;
}
getIndexFromChar('a'); // 0
getIndexFromChar('b'); // 1
================================================
FILE: coding_interviews/javascript/string/charCode.js
================================================
'a'.charCodeAt() - 96; // 1
'b'.charCodeAt() - 96; // 2
================================================
FILE: coding_interviews/javascript/string/isString.js
================================================
function isString(str) {
return typeof str === 'string' || str instanceof String;
}
================================================
FILE: coding_interviews/javascript/string/methods.js
================================================
const string = 'nihongo';
string.replace('n', 'N'); // 'Nihongo'
string.replaceAll('n', 'N'); // 'NihoNgo'
string.slice(2, 4); // 'ho'
string.toUpperCase(); // 'NIHONGO'
string.toUpperCase().toLowerCase(); // 'nihongo'
' nihongo '.trim(); // 'nihongo'
================================================
FILE: coding_interviews/javascript/string/sort.js
================================================
function sort(string) {
return [...string].sort((c1, c2) => c1.localeCompare(c2)).join('');
}
================================================
FILE: coding_interviews/javascript/tree/inorder.js
================================================
/*
TreeNode {
value: int
left: TreeNode | null
right: TreeNode | null
}
*/
function inorder(node) {
if (!node) return;
inorder(node.left);
node.value;
inorder(node.right);
}
================================================
FILE: coding_interviews/javascript/tree/postorder.js
================================================
/*
TreeNode {
value: int
left: TreeNode | null
right: TreeNode | null
}
*/
function postorder(node) {
if (!node) return;
postorder(node.left);
postorder(node.right);
node.value;
}
================================================
FILE: coding_interviews/javascript/tree/preorder.js
================================================
/*
TreeNode {
value: int
left: TreeNode | null
right: TreeNode | null
}
*/
function preorder(node) {
if (!node) return;
node.value;
preorder(node.left);
preorder(node.right);
}
================================================
FILE: coding_interviews/leetcode/easy/a-number-after-a-double-reversal/a-number-after-a-double-reversal.js
================================================
function reverse(numString) {
const stringArray = [];
for (let i = numString.length - 1; i >= 0; i--) {
stringArray.push(numString[i]);
}
return stringArray.join('');
}
function removeLeadingZeros(numString) {
const numStringWithoutLeadingZeros = [];
let foundFirstNonLeadingZero = false;
for (let i = 0; i < numString.length; i++) {
const digitChar = numString[i];
if (
(!foundFirstNonLeadingZero && digitChar !== '0') ||
foundFirstNonLeadingZero
) {
foundFirstNonLeadingZero = true;
numStringWithoutLeadingZeros.push(digitChar);
}
}
return numStringWithoutLeadingZeros.join('');
}
export function isSameAfterReversals(num) {
const numString = num.toString();
if (numString.length === 1) {
return true;
}
const reversedNumString = removeLeadingZeros(reverse(numString));
return numString === reverse(reversedNumString);
}
================================================
FILE: coding_interviews/leetcode/easy/a-number-after-a-double-reversal/tests/a-number-after-a-double-reversal.test.js
================================================
import { describe, it, expect } from 'vitest';
import { isSameAfterReversals } from '../a-number-after-a-double-reversal';
describe('isSameAfterReversals', () => {
it('', () => {
expect(isSameAfterReversals(526)).toBeTruthy();
});
it('', () => {
expect(isSameAfterReversals(1800)).toBeFalsy();
});
it('', () => {
expect(isSameAfterReversals(0)).toBeTruthy();
});
it('', () => {
expect(isSameAfterReversals(609576)).toBeTruthy();
});
});
================================================
FILE: coding_interviews/leetcode/easy/add-digits/add-digits.js
================================================
/*
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Input: num = 0
Output: 0
*/
function isSingleDigit(number) {
return Math.floor(number / 10) === 0;
}
function addDigits(number) {
let result = number;
let sumOfDigits = 0;
while (!isSingleDigit(result)) {
while (result) {
digit = result % 10;
result = Math.floor(result / 10);
sumOfDigits += digit;
}
result = sumOfDigits;
sumOfDigits = 0;
}
return result;
}
console.log('addDigits', addDigits(38));
console.log('addDigits', addDigits(0));
================================================
FILE: coding_interviews/leetcode/easy/add-two-integers/index.js
================================================
const sum = (num1, num2) => num1 + num2;
================================================
FILE: coding_interviews/leetcode/easy/alternating-digit-sum/alternating-digit-sum.js
================================================
function isEvent(num) {
return num % 2 === 0;
}
function alternateDigitSum(n) {
let output = 0;
let nString = n.toString();
for (let index = 0; index < nString.length; index++) {
if (isEvent(index)) output += Number(nString[index]);
else output += Number(nString[index]) * -1;
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/apply-operations-to-an-array/apply-operations-to-an-array.js
================================================
function applyOperations(nums) {
for (let index = 0; index < nums.length - 1; index++) {
if (nums[index] === nums[index + 1]) {
nums[index] *= 2;
nums[index + 1] = 0;
}
}
let zeros = 0;
for (let num of nums) {
if (num === 0) zeros++;
}
let result = [];
for (let num of nums) {
if (num !== 0) {
result.push(num);
}
}
for (let index = 1; index <= zeros; index++) {
result.push(0);
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/arithmetic_progression/arithmetic_progression.py
================================================
# https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence
def can_make_arithmetic_progression(arr):
sorted_arr, diff = sorted(arr), '-Inf'
for index in range(len(sorted_arr) - 1):
if diff == '-Inf':
diff = sorted_arr[index + 1] - sorted_arr[index]
if sorted_arr[index + 1] - sorted_arr[index] != diff:
return False
return True
================================================
FILE: coding_interviews/leetcode/easy/array_partition.py
================================================
'''
https://leetcode.com/problems/array-partition-i/description/
Input: [1,4,3,2]
Output: 4
'''
def array_pair_sum(nums):
return sum(sorted(nums)[::2])
print(array_pair_sum([1, 4, 3, 2]))
================================================
FILE: coding_interviews/leetcode/easy/average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.js
================================================
function averageOfLevels(root) {
const queue = [];
const averageOfLevels = [];
queue.push(root);
while (queue.length) {
let sumOfLevelNodes = 0;
let levelNumberOfNodes = queue.length;
for (let node of queue) {
sumOfLevelNodes += node.val;
}
averageOfLevels.push(sumOfLevelNodes / queue.length);
for (let index = 0; index < levelNumberOfNodes; index++) {
const node = queue.shift();
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
return averageOfLevels;
}
================================================
FILE: coding_interviews/leetcode/easy/average-salary-excluding-the-minimum-and-maximum-salary/average-salary-excluding-the-minimum-and-maximum-salary.js
================================================
function average(salaries) {
let min = Infinity;
let max = -Infinity;
let sum = 0;
for (let salary of salaries) {
min = Math.min(min, salary);
max = Math.max(max, salary);
sum += salary;
}
sum -= min + max;
return sum / (salaries.length - 2);
}
================================================
FILE: coding_interviews/leetcode/easy/average-value-of-even-numbers-that-are-divisible-by-three/average-value-of-even-numbers-that-are-divisible-by-three.js
================================================
// https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three
function isEven(num) {
return num % 2 === 0;
}
function isDividedBy3(num) {
return num % 3 === 0;
}
function averageValue(nums) {
let n = 0;
let sum = 0;
for (let num of nums) {
if (isEven(num) && isDividedBy3(num)) {
n++;
sum += num;
}
}
return n ? Math.floor(sum / n) : 0;
}
================================================
FILE: coding_interviews/leetcode/easy/backspace-string-compare/index.js
================================================
function buildStack(string) {
const stack = [];
for (let index = 0; index < string.length; index++) {
if (string[index] === '#') {
stack.pop();
} else {
stack.push(string[index]);
}
}
return stack;
}
function isEqual(stack1, stack2) {
if (stack1.length !== stack2.length) {
return false;
}
for (let index = 0; index < stack1.length; index++) {
if (stack1[index] !== stack2[index]) {
return false;
}
}
return true;
}
export function backspaceCompare(s, t) {
const sStack = buildStack(s);
const tStack = buildStack(t);
return isEqual(sStack, tStack);
}
================================================
FILE: coding_interviews/leetcode/easy/backspace-string-compare/tests/index.test.js
================================================
import { describe, expect, it } from 'vitest';
import { backspaceCompare } from '../';
describe('backspaceCompare', () => {
it('', () => {
expect(backspaceCompare('ab#c', 'ad#c')).toBeTruthy();
});
it('', () => {
expect(backspaceCompare('ab##', 'c#d#')).toBeTruthy();
});
it('', () => {
expect(backspaceCompare('a#c', 'b')).toBeFalsy();
});
});
================================================
FILE: coding_interviews/leetcode/easy/baseball-game/baseball-game.js
================================================
function calPoints(ops) {
const record = [];
for (let op of ops) {
if (op === 'C') {
record.pop();
} else if (op === 'D') {
const lastOp = record[record.length - 1];
record.push(lastOp * 2);
} else if (op === '+') {
const lastOp = record[record.length - 1];
const penultimateOp = record[record.length - 2];
record.push(lastOp + penultimateOp);
} else {
record.push(Number(op));
}
}
return record.reduce((recordItem, sum) => sum + recordItem, 0);
}
================================================
FILE: coding_interviews/leetcode/easy/best-poker-hand/best-poker-hand.js
================================================
// https://leetcode.com/problems/best-poker-hand
function buildMap(list) {
let map = new Map();
for (let item of list) {
if (map.has(item)) map.set(item, map.get(item) + 1);
else map.set(item, 1);
}
return map;
}
function bestHand(ranks, suits) {
let suitsMap = buildMap(suits);
for (let [_, count] of suitsMap.entries()) {
if (count >= 5) return 'Flush';
}
let ranksMap = buildMap(ranks);
let hasPair = false;
for (let [_, count] of ranksMap.entries()) {
if (count >= 3) return 'Three of a Kind';
if (count >= 2) hasPair = true;
}
return hasPair ? 'Pair' : 'High Card';
}
================================================
FILE: coding_interviews/leetcode/easy/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock-tle.js
================================================
function maxProfit(prices) {
let max = 0;
for (let index = 0; index < prices.length; index++) {
for (
let compareIndex = index + 1;
compareIndex < prices.length;
compareIndex++
) {
max = Math.max(max, prices[compareIndex] - prices[index]);
}
}
return max;
}
================================================
FILE: coding_interviews/leetcode/easy/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.js
================================================
function maxProfit(prices) {
let max = 0;
let buy = 0;
let sell = 1;
while (sell < prices.length) {
if (prices[buy] < prices[sell]) {
let profit = prices[sell] - prices[buy];
max = Math.max(max, profit);
} else {
buy = sell;
}
sell++;
}
return max;
}
================================================
FILE: coding_interviews/leetcode/easy/binary-number-with-alternating-bits/binary-number-with-alternating-bits.js
================================================
function toBinary(n) {
let binary = [];
while (n) {
binary.push((n % 2).toString());
n = Math.floor(n / 2);
}
return binary.join('');
}
function isAlternating(binary) {
let previous = binary[0];
for (let index = 1; index < binary.length; index++) {
let current = binary[index];
if (previous === current) return false;
previous = current;
}
return true;
}
function hasAlternatingBits(n) {
return isAlternating(toBinary(n));
}
================================================
FILE: coding_interviews/leetcode/easy/binary-search/binary-search.js
================================================
function search(nums, target) {
let start = 0;
let end = nums.length - 1;
let middle = Math.floor((end + start) / 2);
let index = -1;
let found = false;
while (start <= end && !found) {
if (target > nums[middle]) {
start = middle + 1;
middle = Math.floor((end + start) / 2);
} else if (target < nums[middle]) {
end = middle - 1;
middle = Math.floor((end + start) / 2);
} else {
index = middle;
found = true;
}
}
return index;
}
================================================
FILE: coding_interviews/leetcode/easy/binary-tree-inorder-traversal/binary-tree-inorder-traversal.js
================================================
function inorderTraversal(root) {
if (!root) {
return [];
}
return [
...inorderTraversal(root.left),
root.val,
...inorderTraversal(root.right),
];
}
================================================
FILE: coding_interviews/leetcode/easy/binary-tree-paths/binary-tree-paths.js
================================================
function traversal(node, paths, path) {
if (!node.left && !node.right) {
paths.push(path.join('->'));
}
if (node.left) {
traversal(node.left, paths, [...path, node.left.val]);
}
if (node.right) {
traversal(node.right, paths, [...path, node.right.val]);
}
}
function binaryTreePaths(root) {
let paths = [];
traversal(root, paths, [root.val]);
return paths;
}
================================================
FILE: coding_interviews/leetcode/easy/binary-tree-postorder-traversal/binary-tree-postorder-traversal.js
================================================
function postorderTraversal(root) {
if (!root) {
return [];
}
return [
...postorderTraversal(root.left),
...postorderTraversal(root.right),
root.val,
];
}
================================================
FILE: coding_interviews/leetcode/easy/binary-tree-preorder-traversal/binary-tree-preorder-traversal.js
================================================
function preorderTraversal(root) {
if (!root) {
return [];
}
return [
root.val,
...preorderTraversal(root.left),
...preorderTraversal(root.right),
];
}
================================================
FILE: coding_interviews/leetcode/easy/binary-tree-tilt/binary-tree-tilt-optimized.js
================================================
// https://leetcode.com/problems/binary-tree-tilt
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
let sum;
function sumNodes(node) {
if (!node) return 0;
let leftSum = sumNodes(node.left);
let rightSum = sumNodes(node.right);
sum += Math.abs(leftSum - rightSum);
return node.val + leftSum + rightSum;
}
function findTilt(root) {
sum = 0;
sumNodes(root);
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/binary-tree-tilt/binary-tree-tilt.js
================================================
// https://leetcode.com/problems/binary-tree-tilt
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
function sumNodes(node) {
if (!node) return 0;
return node.val + sumNodes(node.left) + sumNodes(node.right);
}
function findTilt(root) {
if (!root) return 0;
return (
Math.abs(sumNodes(root.left) - sumNodes(root.right)) +
findTilt(root.left) +
findTilt(root.right)
);
}
================================================
FILE: coding_interviews/leetcode/easy/binary_in_linked_list/binary_in_linked_list.py
================================================
def get_decimal_value(head):
numbers = [head.val]
while head.next:
head = head.next
numbers.append(head.val)
decimal_number = 0
base = 1
for index in range(len(numbers)):
decimal_number += base * numbers[len(numbers) - index - 1]
base *= 2
return decimal_number
================================================
FILE: coding_interviews/leetcode/easy/build_an_array_with_stack_operations/build_an_array_with_stack_operations.py
================================================
# https://leetcode.com/problems/build-an-array-with-stack-operations
def build_array(target, n):
hash = {}
for num in target:
hash[num] = True
result = []
for num in range(1, n + 1):
if len(hash) == 0: break
result.append('Push')
if num in hash: del hash[num]
else: result.append('Pop')
return result
def build_array(target, n):
s = set(target)
result = []
for index in range(1, target[-1] + 1):
result.append('Push')
if index not in s: result.append('Pop')
return result
================================================
FILE: coding_interviews/leetcode/easy/build_array_from_permutation/build_array_from_permutation.js
================================================
// https://leetcode.com/problems/build-array-from-permutation
const buildArray = function (nums) {
return nums.map((num) => nums[num]);
};
================================================
FILE: coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates-on.js
================================================
// https://leetcode.com/problems/buy-two-chocolates
function buyChoco(prices, money) {
let min1 = Infinity;
let min2 = Infinity;
for (let num of prices) {
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num <= min2) {
min2 = num;
}
}
return money - min1 - min2 >= 0 ? money - min1 - min2 : money;
}
================================================
FILE: coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates-sort.js
================================================
// https://leetcode.com/problems/buy-two-chocolates
function buyChoco(prices, money) {
prices.sort((a, b) => a - b);
const first = prices[0];
const second = prices[1];
const diff = money - first - second;
return diff >= 0 ? diff : money;
}
================================================
FILE: coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates.js
================================================
// https://leetcode.com/problems/buy-two-chocolates
function buyChocolate(prices, money) {
let price = Infinity;
let priceIndex = 0;
for (let index = 0; index < prices.length; index++) {
if (prices[index] <= money && prices[index] < price) {
price = prices[index];
priceIndex = index;
}
}
prices[priceIndex] = Infinity;
return money - price;
}
function buyChoco(prices, money) {
let restMoney = buyChocolate(prices, buyChocolate(prices, money));
return restMoney >= 0 ? restMoney : money;
}
================================================
FILE: coding_interviews/leetcode/easy/calculate-amount-paid-in-taxes/calculate-amount-paid-in-taxes.js
================================================
// https://leetcode.com/problems/calculate-amount-paid-in-taxes
function calculateTax(brackets, income) {
let taxes = 0;
let appliedIncome = 0;
let moneyToApplyTax;
let tax;
for (let index = 0; index < brackets.length && income > 0; index++) {
moneyToApplyTax = Math.min(income, brackets[index][0] - appliedIncome);
appliedIncome += moneyToApplyTax;
tax = moneyToApplyTax * (brackets[index][1] / 100);
taxes += tax;
income -= moneyToApplyTax;
}
return taxes;
}
================================================
FILE: coding_interviews/leetcode/easy/calculate-delayed-arrival-time/calculate-delayed-arrival-time.js
================================================
// https://leetcode.com/problems/calculate-delayed-arrival-time
function findDelayedArrivalTime(arrivalTime, delayedTime) {
return (arrivalTime + delayedTime) % 24;
}
================================================
FILE: coding_interviews/leetcode/easy/calculate-digit-sum-of-a-string/calculate-digit-sum-of-a-string.js
================================================
function buildSubsets(s, k) {
const subsets = [];
for (let index = 0; index < s.length; index += k) {
subsets.push(s.substring(index, index + k));
}
return subsets;
}
function sumDigits(digits) {
let sumOfDigits = 0;
for (let digit of digits) {
sumOfDigits += Number(digit);
}
return sumOfDigits;
}
function sumDigitsOfSubsets(subsets) {
return subsets.map(sumDigits);
}
function digitSum(s, k) {
if (s.length <= k) return s;
const subsets = buildSubsets(s, k);
const sumOfDigitsOfSubsets = sumDigitsOfSubsets(subsets);
const newString = sumOfDigitsOfSubsets.join('');
return digitSum(newString, k);
}
================================================
FILE: coding_interviews/leetcode/easy/calculate-money-in-leetcode-bank/calculate-money-in-leetcode-bank.js
================================================
function totalMoney(n) {
let monday = 0;
let previousDay = monday;
let counter = monday;
for (let index = 0; index < n; index++) {
if (index % 7 === 0) {
monday++;
counter += monday;
previousDay = monday;
} else {
previousDay++;
counter += previousDay;
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/can-place-flowers/can-place-flowers.js
================================================
function canPlaceFlowers(flowerbed, n) {
let counter = 0;
for (let index = 0; index < flowerbed.length; index++) {
if (flowerbed[index] === 0) {
let isLeftPlotEmpty = index === 0 || flowerbed[index - 1] === 0;
let isRightPlotEmpty =
index === flowerbed.length - 1 || flowerbed[index + 1] === 0;
if (isLeftPlotEmpty && isRightPlotEmpty) {
flowerbed[index] = 1;
counter++;
}
}
}
return counter >= n;
}
================================================
FILE: coding_interviews/leetcode/easy/capitalize-the-title/capitalize-the-title.js
================================================
function isUppercase(char) {
return char.charCodeAt() >= 65 && char.charCodeAt() <= 90;
}
function isLowercase(char) {
return char.charCodeAt() >= 97 && char.charCodeAt() <= 122;
}
function capitalizeChar(char) {
return isUppercase(char) ? char : String.fromCharCode(char.charCodeAt() - 32);
}
function lowercaseChar(char) {
return isLowercase(char) ? char : String.fromCharCode(char.charCodeAt() + 32);
}
function capitalize(string) {
return capitalizeChar(string[0]) + lowercase(string.slice(1));
}
function lowercase(string) {
return string.split('').map(lowercaseChar).join('');
}
function parse(string) {
return string.length <= 2 ? lowercase(string) : capitalize(string);
}
function capitalizeTitle(title) {
return title.split(' ').map(parse).join(' ');
}
================================================
FILE: coding_interviews/leetcode/easy/cells-in-a-range-on-an-excel-sheet/cells-in-a-range-on-an-excel-sheet.js
================================================
const alphabet = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ';
export function cellsInRange(s) {
const result = [];
for (
let alpha = alphabet.indexOf(s[0]);
alpha <= alphabet.indexOf(s[3]);
alpha++
) {
for (let i = Number(s[1]); i <= Number(s[4]); i++) {
result.push(alphabet[alpha] + i.toString());
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/cells-in-a-range-on-an-excel-sheet/tests/cells-in-a-range-on-an-excel-sheet.test.js
================================================
import { describe, it, expect } from 'vitest';
import { cellsInRange } from '../cells-in-a-range-on-an-excel-sheet';
describe('cellsInRange', () => {
it('', () => {
expect(cellsInRange('U7:X9')).toEqual([
'U7',
'U8',
'U9',
'V7',
'V8',
'V9',
'W7',
'W8',
'W9',
'X7',
'X8',
'X9',
]);
});
it('', () => {
expect(cellsInRange('P7:Z7')).toEqual([
'P7',
'Q7',
'R7',
'S7',
'T7',
'U7',
'V7',
'W7',
'X7',
'Y7',
'Z7',
]);
});
it('', () => {
expect(cellsInRange('K1:L2')).toEqual(['K1', 'K2', 'L1', 'L2']);
});
it('', () => {
expect(cellsInRange('A1:F1')).toEqual(['A1', 'B1', 'C1', 'D1', 'E1', 'F1']);
});
it('', () => {
expect(cellsInRange('K2:L3')).toEqual(['K2', 'K3', 'L2', 'L3']);
});
});
================================================
FILE: coding_interviews/leetcode/easy/check-array-formation-through-concatenation/check-array-formation-through-concatenation.js
================================================
function buildMap(pieces) {
let hashmap = new Map();
for (let piece of pieces) {
hashmap.set(piece[0], piece);
}
return hashmap;
}
function canFormArray(arr, pieces) {
let index = 0;
let hashmap = buildMap(pieces);
let output = [];
while (index < arr.length) {
let num = arr[index];
if (!hashmap.has(num)) return false;
output = [...output, ...hashmap.get(num)];
index += hashmap.get(num).length;
}
if (arr.length !== output.length) return false;
for (let index = 0; index < arr.length; index++) {
if (arr[index] !== output[index]) return false;
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/check-distances-between-same-letters/check-distances-between-same-letters.js
================================================
function getDistanceIndex(char) {
return char.charCodeAt() - 97;
}
function checkDistances(string, distance) {
const hashmap = new Map();
for (let index = 0; index < string.length; index++) {
const char = string[index];
if (hashmap.has(char)) {
const distanceIndex = getDistanceIndex(char);
const charDistance = distance[distanceIndex];
const previousIndex = hashmap.get(char);
if (index - previousIndex - 1 !== charDistance) return false;
} else {
hashmap.set(char, index);
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-a-string-is-an-acronym-of-words/check-if-a-string-is-an-acronym-of-words.js
================================================
// https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words
function isAcronym(words, s) {
if (words.length !== s.length) return false;
for (let index = 0; index < s.length; index++) {
if (words[index][0] !== s[index]) {
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js
================================================
function hasPrefix(word, searchWord) {
if (searchWord.length > word.length) return false;
for (let index = 0; index < searchWord.length; index++) {
if (searchWord[index] !== word[index]) return false;
}
return true;
}
function isPrefixOfWord(sentence, searchWord) {
const words = sentence.split(' ');
for (let index = 0; index < words.length; index++) {
if (hasPrefix(words[index], searchWord)) return index + 1;
}
return -1;
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-all-as-appears-before-all-bs/check-if-all-as-appears-before-all-bs.js
================================================
function checkString(s) {
let gotFirstB = false;
for (let char of s) {
if (char === 'b' && !gotFirstB) {
gotFirstB = true;
}
if (char === 'a' && gotFirstB) {
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-matrix-is-x-matrix/check-if-matrix-is-x-matrix.js
================================================
function isInGrid(grid, row, col) {
return row >= 0 && col >= 0 && row < grid.length && col < grid.length;
}
const DIAGONAL = -1;
function getDiagonalFromLeftToRight(grid) {
let row = 0;
let col = 0;
let values = [];
while (isInGrid(grid, row, col)) {
values.push(grid[row][col]);
grid[row][col] = DIAGONAL;
row++;
col++;
}
return values;
}
function getDiagonalFromRightToLeft(grid) {
let row = 0;
let col = grid.length - 1;
let values = [];
while (isInGrid(grid, row, col)) {
if (grid[row][col] !== DIAGONAL) {
values.push(grid[row][col]);
grid[row][col] = DIAGONAL;
}
row++;
col--;
}
return values;
}
function isDiagonalNonZero(diagonal) {
return diagonal.filter((value) => value === 0).length === 0;
}
function isOtherZero(grid) {
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid.length; col++) {
if (grid[row][col] !== DIAGONAL && grid[row][col] !== 0) {
return false;
}
}
}
return true;
}
function checkXMatrix(grid) {
const fromLeftToRightDiagonalValues = getDiagonalFromLeftToRight(grid);
const fromRightToLeftDiagonalValues = getDiagonalFromRightToLeft(grid);
const isFromLeftToRightNonZero = isDiagonalNonZero(
fromLeftToRightDiagonalValues
);
const isFromRightToLeftNonZero = isDiagonalNonZero(
fromRightToLeftDiagonalValues
);
const isOtherElementsZero = isOtherZero(grid);
return (
isFromLeftToRightNonZero && isFromRightToLeftNonZero && isOtherElementsZero
);
}
function checkXMatrix(grid) {
const n = grid.length;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (i == j || i + j + 1 == n) {
if (grid[i][j] == 0) return false;
} else {
if (grid[i][j] != 0) return false;
}
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-number-has-equal-digit-count-and-digit-value/check-if-number-has-equal-digit-count-and-digit-value.js
================================================
function digitCount(num) {
let counter = new Map();
for (let digit of num) {
if (counter.has(digit)) {
counter.set(digit, counter.get(digit) + 1);
} else {
counter.set(digit, 1);
}
}
for (let index = 0; index < num.length; index++) {
let digit = num[index];
let indexString = index.toString();
if (
counter.has(indexString) &&
counter.get(indexString) !== Number(digit)
) {
return false;
}
if (!counter.has(indexString) && digit !== '0') {
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-numbers-are-ascending-in-a-sentence/check-if-numbers-are-ascending-in-a-sentence.js
================================================
function getNumbers(string) {
const tokens = string.split(' ');
const numbersStrings = tokens.filter((token) => !Number.isNaN(Number(token)));
return numbersStrings.map((numberString) => Number(numberString));
}
function isIncreasing(numbers) {
for (let index = 0; index < numbers.length - 1; index++) {
if (numbers[index + 1] <= numbers[index]) return false;
}
return true;
}
function areNumbersAscending(string) {
const numbers = getNumbers(string);
return isIncreasing(numbers);
}
================================================
FILE: coding_interviews/leetcode/easy/check-if-the-sentence-is-pangram/check-if-the-sentence-is-pangram.py
================================================
# https://leetcode.com/problems/check-if-the-sentence-is-pangram
def check_if_pangram(sentence):
if len(sentence) < 26: return False
unique_chars = set()
for char in sentence:
unique_chars.add(char)
return len(unique_chars) == 26
def check_if_pangram(sentence):
return len(set(sentence)) == 26
================================================
FILE: coding_interviews/leetcode/easy/check-whether-two-strings-are-almost-equivalent/check-whether-two-strings-are-almost-equivalent.js
================================================
function createCounter(word) {
const counter = new Map();
for (let char of word) {
if (counter.has(char)) counter.set(char, counter.get(char) + 1);
else counter.set(char, 1);
}
return counter;
}
function isSimilar(word, counter1, counter2) {
for (let char of word) {
const count1 = counter1.get(char);
const count2 = (counter2.has(char) && counter2.get(char)) || 0;
if (Math.abs(count1 - count2) > 3) return false;
}
return true;
}
function checkAlmostEquivalent(word1, word2) {
const word1Counter = createCounter(word1);
const word2Counter = createCounter(word2);
return (
isSimilar(word1, word1Counter, word2Counter) &&
isSimilar(word2, word2Counter, word1Counter)
);
}
================================================
FILE: coding_interviews/leetcode/easy/check_if_all_characters_have_equal_number_of_occurrences/check_if_all_characters_have_equal_number_of_occurrences.js
================================================
// https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences
const areOccurrencesEqual = function (s) {
const counter = {};
for (let i = 0; i < s.length; i++) {
if (s[i] in counter) counter[s[i]]++;
else counter[s[i]] = 1;
}
return new Set(Object.values(counter)).size === 1;
};
================================================
FILE: coding_interviews/leetcode/easy/check_if_two_string_arrays_are_equivalent/check_if_two_string_arrays_are_equivalent.py
================================================
# https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent
def array_strings_are_equal(word1, word2):
return ''.join(word1) == ''.join(word2)
================================================
FILE: coding_interviews/leetcode/easy/circular-sentence/circular-sentence.js
================================================
function isCircularSentence(sentence) {
const words = sentence.split(' ');
const lastWord = words[words.length - 1];
const lastCharEqualFirstChar = lastWord[lastWord.length - 1] === words[0][0];
if (!lastCharEqualFirstChar) return false;
for (let index = 0; index < words.length - 1; index++) {
const firstWord = words[index];
const nextWord = words[index + 1];
if (firstWord[firstWord.length - 1] !== nextWord[0]) return false;
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/climbing-stairs/climbing-stairs.js
================================================
function climbStairs(n) {
let memo = [0, 1, 2, 3];
for (let i = 4; i <= n; i++) {
memo.push(memo[i - 1] + memo[i - 2]);
}
return memo[n];
}
================================================
FILE: coding_interviews/leetcode/easy/climbing_stairs.py
================================================
# https://leetcode.com/problems/climbing-stairs/description/
def climb_stairs(n):
memo = [0, 1, 2, 3]
for i in range(4, n + 1):
memo.append(memo[i - 1] + memo[i - 2])
return memo[n]
print climb_stairs(1)
print climb_stairs(2)
print climb_stairs(3)
print climb_stairs(4)
print climb_stairs(5)
print climb_stairs(6)
================================================
FILE: coding_interviews/leetcode/easy/concatenation_of_array/concatenation_of_array.js
================================================
const getConcatenation = function (nums) {
nums.forEach((num) => nums.push(num));
return nums;
};
const getConcatenation = function (nums) {
return [...nums, ...nums];
};
================================================
FILE: coding_interviews/leetcode/easy/consecutive-characters/consecutive-characters.js
================================================
function maxPower(string) {
let power = 1;
let max = 1;
let currentChar = string[0];
for (let index = 1; index < string.length; index++) {
let char = string[index];
if (char === currentChar) max++;
if (char !== currentChar || index === string.length - 1) {
currentChar = char;
power = Math.max(max, power);
max = 1;
}
}
return power;
}
================================================
FILE: coding_interviews/leetcode/easy/construct-string-from-binary-tree/construct-string-from-binary-tree.js
================================================
// https://leetcode.com/problems/construct-string-from-binary-tree
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
// Time complexity : O(n). The preorder traversal is done over the n nodes of the given Binary Tree.
// Space complexity : O(n). The depth of the recursion tree can go upto n in case of a skewed tree.
function tree2str(root) {
if (!root) return '';
let left = tree2str(root.left);
let right = tree2str(root.right);
if (right) {
return `${root.val}(${left})(${right})`;
}
if (left) {
return `${root.val}(${left})`;
}
return root.val.toString();
}
================================================
FILE: coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate-hashmap.js
================================================
/*
nums = [1,2,3,4,4]
numToCounter = {
1: 1,
2: 1,
3: 1,
4: 2
}
*/
function containsDuplicate(nums) {
let numToCounter = {};
let appearsAtLeastTwice = false;
for (let num of nums) {
if (numToCounter[num]) {
numToCounter[num]++;
} else {
numToCounter[num] = 1;
}
}
Object.values(numToCounter).forEach((num) => {
if (num >= 2) {
appearsAtLeastTwice = true;
}
});
return appearsAtLeastTwice;
}
================================================
FILE: coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.js
================================================
function containsDuplicate(nums) {
return !(nums.length === new Set(nums).size);
}
================================================
FILE: coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.py
================================================
# https://leetcode.com/problems/contains-duplicate-ii
def contains_nearby_duplicate(nums, k):
for index in range(len(nums)):
for comp_index in range(len(nums)):
if index != comp_index and nums[index] == nums[comp_index] and abs(comp_index - index) <= k:
return True
return False
def contains_nearby_duplicate(nums, k):
index_mapper = {}
for index, num in enumerate(nums):
if num in index_mapper and index - index_mapper[num] <= k: return True
index_mapper[num] = index
return False
================================================
FILE: coding_interviews/leetcode/easy/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.js
================================================
function sortedArrayToBST(nums) {
if (nums.length === 0) return null;
const middle = Math.floor(nums.length / 2);
const num = nums[middle];
const node = new TreeNode(num);
node.left = sortedArrayToBST(nums.slice(0, middle));
node.right = sortedArrayToBST(nums.slice(middle + 1, nums.length));
return node;
}
================================================
FILE: coding_interviews/leetcode/easy/convert-the-temperature/convert-the-temperature.js
================================================
function convertTemperature(celsius) {
return [celsius + 273.15, celsius * 1.8 + 32.0];
}
================================================
FILE: coding_interviews/leetcode/easy/count-asterisks/count-asterisks.js
================================================
function toggleCanCount(canCount) {
return !canCount;
}
function countAsterisks(s) {
let asteristics = 0;
let canCount = true;
for (let char of s) {
if (canCount && char === '*') {
asteristics++;
}
if (char === '|') {
canCount = toggleCanCount(canCount);
}
}
return asteristics;
}
================================================
FILE: coding_interviews/leetcode/easy/count-common-words-with-one-occurrence/count-common-words-with-one-occurrence.js
================================================
function buildHashmap(words) {
let hashmap = new Map();
for (let word of words) {
if (hashmap.has(word)) {
hashmap.set(word, hashmap.get(word) + 1);
} else {
hashmap.set(word, 1);
}
}
return hashmap;
}
function countWords(words1, words2) {
let words1Counter = buildHashmap(words1);
let words2Counter = buildHashmap(words2);
let words = 0;
for (let [word, counter] of words1Counter) {
if (
counter === 1 &&
words2Counter.has(word) &&
words2Counter.get(word) === 1
) {
words++;
}
}
return words;
}
================================================
FILE: coding_interviews/leetcode/easy/count-complete-tree-nodes/count-complete-tree-nodes.js
================================================
// https://leetcode.com/problems/count-complete-tree-nodes
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
function countNodes(node) {
return node ? 1 + countNodes(node.left) + countNodes(node.right) : 0;
}
================================================
FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/count-equal-and-divisible-pairs-in-an-array-2.js
================================================
/*
list = [3, 1, 2, 2, 2, 1, 3]
data structure
{
3: [0, 6],
1: [1, 5],
2: [2, 3, 4]
}
worst case scenario
{
x: [0, 1, 2, 3, ..., 100]
}
*/
export function countPairs(numbers, k) {
let counter = 0;
for (let i = 0; i < numbers.length - 1; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[i] === numbers[j] && (i * j) % k === 0) {
counter++;
}
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/count-equal-and-divisible-pairs-in-an-array.js
================================================
/*
list = [3, 1, 2, 2, 2, 1, 3]
data structure
{
3: [0, 6],
1: [1, 5],
2: [2, 3, 4]
}
worst case scenario
{
x: [0, 1, 2, 3, ..., 100]
}
*/
export function countPairs(numbers, k) {
const numberToIndices = {};
numbers.forEach((number, index) => {
if (number in numberToIndices) {
numberToIndices[number].push(index);
} else {
numberToIndices[number] = [index];
}
});
let counter = 0;
Object.values(numberToIndices).forEach((indices) => {
for (let i = 0; i < indices.length - 1; i++) {
for (let j = i + 1; j < indices.length; j++) {
if ((indices[i] * indices[j]) % k === 0) {
counter++;
}
}
}
});
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/tests/count-equal-and-divisible-pairs-in-an-array-2.test.js
================================================
import { describe, expect, it } from 'vitest';
import { countPairs } from '../count-equal-and-divisible-pairs-in-an-array-2';
describe('countPairs', () => {
it('', () => {
expect(countPairs([3, 1, 2, 2, 2, 1, 3], 2)).toEqual(4);
});
it('', () => {
expect(countPairs([1, 2, 3, 4], 1)).toEqual(0);
});
});
================================================
FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/tests/count-equal-and-divisible-pairs-in-an-array.test.js
================================================
import { describe, expect, it } from 'vitest';
import { countPairs } from '../count-equal-and-divisible-pairs-in-an-array';
describe('countPairs', () => {
it('', () => {
expect(countPairs([3, 1, 2, 2, 2, 1, 3], 2)).toEqual(4);
});
it('', () => {
expect(countPairs([1, 2, 3, 4], 1)).toEqual(0);
});
});
================================================
FILE: coding_interviews/leetcode/easy/count-good-triplets/count-good-triplets.py
================================================
# https://leetcode.com/problems/count-good-triplets
'''
Time Complexity: O(N^3)
Space Complexity: O(1) - no extra space rather than the input
'''
def count_good_triplets(arr, a, b, c):
counter = 0
for i in range(len(arr)):
for j in range(i+1, len(arr)):
for k in range(j+1, len(arr)):
if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/count-integers-with-even-digit-sum/count-integers-with-even-digit-sum.js
================================================
function sumDigits(numString) {
let sum = 0;
for (let digit of numString) {
sum += Number(digit);
}
return sum;
}
function isEven(num) {
return num % 2 === 0;
}
function countEven(num) {
let counter = 0;
for (let number = 1; number <= num; number++) {
let numString = number.toString();
let digitSum = sumDigits(numString);
if (isEven(digitSum)) counter++;
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-k-difference/count-k-difference.js
================================================
/*
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
Example 2:
Input: nums = [1,3], k = 3
Output: 0
Explanation: There are no pairs with an absolute difference of 3.
Example 3:
Input: nums = [3,2,1,5,4], k = 2
Output: 3
Explanation: The pairs with an absolute difference of 2 are:
- [3,2,1,5,4]
- [3,2,1,5,4]
- [3,2,1,5,4]
*/
function countKDifference(nums, k) {
const numsMap = {};
nums.forEach((num) => {
if (num in numsMap) numsMap[num] += 1;
else numsMap[num] = 1;
});
let count = 0;
nums.forEach((num) => {
const rest = num + k;
if (rest in numsMap) {
count += numsMap[rest];
}
});
return count;
}
console.log(countKDifference([1, 2, 2, 1], 1), 4);
console.log(countKDifference([1, 3], 3), 0);
console.log(countKDifference([3, 2, 1, 5, 4], 2), 3);
console.log(countKDifference([7, 10, 10, 6, 10, 1, 9, 10, 4, 9], 7), 0);
console.log(countKDifference([2, 3, 2, 10, 3, 9, 4, 9, 5, 8], 1), 11);
================================================
FILE: coding_interviews/leetcode/easy/count-largest-group/count-largest-group.js
================================================
// https://leetcode.com/problems/count-largest-group
function sumDigits(num) {
let numString = num.toString();
let sum = 0;
for (let digit of numString) {
sum += Number(digit);
}
return sum;
}
function countLargestGroup(n) {
let hashmap = new Map();
for (let num = 1; num <= n; num++) {
let sum = sumDigits(num);
if (hashmap.has(sum)) hashmap.set(sum, [...hashmap.get(sum), num]);
else hashmap.set(sum, [num]);
}
let largest = -Infinity;
for (let [_, values] of hashmap.entries()) {
largest = Math.max(largest, values.length);
}
let size = 0;
for (let [_, values] of hashmap.entries()) {
if (values.length === largest) size++;
}
return size;
}
================================================
FILE: coding_interviews/leetcode/easy/count-operations-to-obtain-zero/count-operations-to-obtain-zero.js
================================================
export function countOperations(num1, num2) {
let counter = 0;
while (num1 > 0 && num2 > 0) {
if (num1 >= num2) {
num1 -= num2;
} else {
num2 -= num1;
}
counter++;
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-operations-to-obtain-zero/tests/count-operations-to-obtain-zero.test.js
================================================
import { describe, expect, it } from 'vitest';
import { countOperations } from '../count-operations-to-obtain-zero';
describe('countOperations', () => {
it('', () => {
expect(countOperations(2, 3)).toEqual(3);
});
it('', () => {
expect(countOperations(10, 10)).toEqual(1);
});
});
================================================
FILE: coding_interviews/leetcode/easy/count-pairs-of-similar-strings/count-pairs-of-similar-strings.js
================================================
function buildCharsMap(word) {
const map = new Map();
for (let char of word) {
if (map.has(char)) map.set(char, map.get(char) + 1);
else map.set(char, 1);
}
return map;
}
function hasAllChars(word, charsMap) {
for (let char of word) {
if (!charsMap.has(char)) return false;
}
return true;
}
function isSimilar(word1, word2) {
const word1CharsMap = buildCharsMap(word1);
const word2CharsMap = buildCharsMap(word2);
return hasAllChars(word1, word2CharsMap) && hasAllChars(word2, word1CharsMap);
}
function similarPairs(words) {
let count = 0;
for (let i = 0; i < words.length - 1; i++) {
for (let j = i + 1; j < words.length; j++) {
if (isSimilar(words[i], words[j])) count++;
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/count-pairs-whose-sum-is-less-than-target/count-pairs-whose-sum-is-less-than-target-two-pointers.js
================================================
// https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target
function countPairs(nums, target) {
nums.sort((num1, num2) => num1 - num2);
let counter = 0;
let start = 0;
let end = nums.length - 1;
while (start < end) {
if (nums[start] + nums[end] < target) {
counter += end - start;
start++;
} else {
end--;
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-pairs-whose-sum-is-less-than-target/count-pairs-whose-sum-is-less-than-target.js
================================================
// https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target
function countPairs(nums, target) {
let counter = 0;
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] < target) counter++;
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-prefixes-of-a-given-string/count-prefixes-of-a-given-string.js
================================================
function hasPrefix(word, s) {
for (let index = 0; index < word.length; index++) {
if (word[index] !== s[index]) {
return false;
}
}
return true;
}
function countPrefixes(words, s) {
let counter = 0;
for (let word of words) {
if (word.length <= s.length && hasPrefix(word, s)) {
counter++;
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-square-sum-triples/count-square-sum-triples.js
================================================
function countTriples(n) {
let hashmap = new Map();
let counter = 0;
for (let num = 1; num <= n; num++) {
hashmap.set(num * num, num);
}
for (let a = 1; a <= n; a++) {
for (let b = 1; b <= n; b++) {
const c = a * a + b * b;
if (hashmap.has(c)) {
counter++;
}
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/count-symmetric-integers/count-symmetric-integers.js
================================================
// https://leetcode.com/problems/count-symmetric-integers
function isSymmetricIntegers(num) {
let numString = num.toString();
if (numString.length % 2 !== 0) return false;
let firstHalfSum = 0;
let lastHalfSum = 0;
for (let index = 0; index < numString.length; index++) {
let digit = numString[index];
if (index < numString.length / 2) firstHalfSum += Number(digit);
else lastHalfSum += Number(digit);
}
return firstHalfSum === lastHalfSum;
}
function countSymmetricIntegers(low, high) {
let count = 0;
for (let num = low; num <= high; num++) {
if (isSymmetricIntegers(num)) {
count++;
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/count-the-digits-that-divide-a-number/count-the-digits-that-divide-a-number.js
================================================
function countDigits(num) {
let digitsCount = 0;
let numString = num.toString();
for (let numChar of numString) {
if (num % Number(numChar) === 0) digitsCount++;
}
return digitsCount;
}
================================================
FILE: coding_interviews/leetcode/easy/count-the-number-of-vowel-strings-in-range/count-the-number-of-vowel-strings-in-range.js
================================================
const VOWELS = ['a', 'e', 'i', 'o', 'u'];
function isVowelString(string) {
return (
VOWELS.includes(string[0]) && VOWELS.includes(string[string.length - 1])
);
}
function vowelStrings(words, left, right) {
let vowelsStrings = 0;
for (let index = left; index <= right; index++) {
if (isVowelString(words[index])) {
vowelsStrings++;
}
}
return vowelsStrings;
}
================================================
FILE: coding_interviews/leetcode/easy/count-vowel-substrings-of-a-string/count-vowel-substrings-of-a-string.js
================================================
const VOWELS = ['a', 'e', 'i', 'o', 'u'];
function isVowel(char) {
return VOWELS.includes(char);
}
function hasAllVowels(foundVowels) {
return (
foundVowels.has('a') &&
foundVowels.has('e') &&
foundVowels.has('i') &&
foundVowels.has('o') &&
foundVowels.has('u')
);
}
function countVowelSubstrings(word) {
let vowelSubstringCount = 0;
for (let i = 0; i < word.length - 4; i++) {
if (!isVowel(word[i])) continue;
const foundVowels = new Map();
foundVowels.set(word[i], 1);
for (let index = i + 1; index < word.length; index++) {
const char = word[index];
if (!isVowel(char)) break;
if (foundVowels.has(char))
foundVowels.set(char, foundVowels.get(char) + 1);
else foundVowels.set(char, 1);
if (hasAllVowels(foundVowels)) vowelSubstringCount++;
}
}
return vowelSubstringCount;
}
================================================
FILE: coding_interviews/leetcode/easy/count_good_rectangles/count_good_rectangles.py
================================================
# https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square
'''
Time Complexity: O(N)
Space Complexity: O(N)
'''
def count_good_rectangles(rectangles):
max_len, all_max_lens = 0, []
for rec in rectangles:
square_len = min(rec[0], rec[1])
max_len = max(max_len, square_len)
all_max_lens.append(square_len)
counter = 0
for length in all_max_lens:
if length == max_len:
counter += 1
return counter
def count_good_rectangles_optimized(rectangles):
max_len, counter = 0, 0
for rec in rectangles:
square_len = min(rec[0], rec[1])
if square_len > max_len:
max_len = square_len
counter = 0
if square_len == max_len:
counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/count_matches/count_matches.py
================================================
# https://leetcode.com/problems/count-items-matching-a-rule
def count_matches(items, ruleKey, ruleValue):
counter = 0
for item in items:
if ruleKey == 'type' and item[0] == ruleValue: counter += 1
if ruleKey == 'color' and item[1] == ruleValue: counter += 1
if ruleKey == 'name' and item[2] == ruleValue: counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/count_of_matches_in_tournament/count_of_matches_in_tournament.py
================================================
# https://leetcode.com/problems/count-of-matches-in-tournament
'''
Runtime: O(N)
Space: O(1)
'''
def number_of_matches(n):
if n <= 0:
return 0
number_of_games = 0
while n > 1:
games = n // 2
number_of_games += games
if n % 2 == 0:
n = games
else:
n = games + 1
return number_of_games
================================================
FILE: coding_interviews/leetcode/easy/count_students/count_students.py
================================================
# https://leetcode.com/problems/number-of-students-unable-to-eat-lunch
def is_empty(arr):
return len(arr) == 0
def count_students(students, sandwiches):
preferred_circles = 0
preferred_squares = 0
for student in students:
if student:
preferred_squares += 1
else:
preferred_circles += 1
while not is_empty(students) and not is_empty(sandwiches):
if students[0] == sandwiches[0]:
if students[0]:
preferred_squares -= 1
else:
preferred_circles -= 1
del students[0]
del sandwiches[0]
else:
students.append(students[0])
del students[0]
if not is_empty(sandwiches) and (sandwiches[0] and preferred_squares == 0 or sandwiches[0] == 0 and preferred_circles == 0):
break
return len(students)
def count_students(students, sandwiches):
preferences = [0, 0]
for student in students:
preferences[student] += 1
index = 0
while index < len(students):
if preferences[sandwiches[index]] > 0:
preferences[sandwiches[index]] -= 1
else:
break
index += 1
return len(students) - index
================================================
FILE: coding_interviews/leetcode/easy/count_the_number_of_consistent_strings/count_the_number_of_consistent_strings.py
================================================
# https://leetcode.com/problems/count-the-number-of-consistent-strings
'''
Time complexity: O(WN), where W = number of words and N = number of character of the longest string
Space complexity: O(N)
'''
def count_consistent_strings(allowed, words):
allowed_mapper = {}
for char in allowed:
allowed_mapper[char] = True
counter = 0
for word in words:
all_chars_allowed = True
for char in word:
if char not in allowed_mapper:
all_chars_allowed = False
break
if all_chars_allowed:
counter += 1
return counter
'''
Time complexity: O(WNA), where W = number of words and N = number of character of the longest string, and A = length of the allowed string
Space complexity: O(1)
'''
def count_consistent_strings(allowed, words):
counter = 0
for word in words:
counter += 1
for char in word:
if char not in allowed:
counter -= 1
break
return counter
================================================
FILE: coding_interviews/leetcode/easy/counting-bits/counting-bits.js
================================================
function countOnesInBinaryTransformation(number) {
let counter = 0;
while (number) {
let remainder = number % 2;
if (remainder) counter++;
number = Math.floor(number / 2);
}
return counter;
}
function countBits(n) {
let answer = [];
for (let num = 0; num <= n; num++) {
answer.push(countOnesInBinaryTransformation(num));
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/easy/counting-words-with-a-given-prefix/counting-words-with-a-given-prefix.js
================================================
function hasPrefix(word, pref) {
if (pref.length > word.length) {
return false;
}
let matchesPrefix = true;
for (let i = 0; i < pref.length; i++) {
if (word[i] !== pref[i]) {
matchesPrefix = false;
break;
}
}
return matchesPrefix;
}
export function prefixCount(words, pref) {
let count = 0;
words.forEach((word) => {
if (hasPrefix(word, pref)) {
count++;
}
});
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/counting-words-with-a-given-prefix/tests/counting-words-with-a-given-prefix.test.js
================================================
import { describe, it, expect } from 'vitest';
import { prefixCount } from '../counting-words-with-a-given-prefix';
describe('prefixCount', () => {
it('matches 2 words', () => {
expect(
prefixCount(['pay', 'attention', 'practice', 'attend'], 'at')
).toEqual(2);
});
it('matches 3 words', () => {
expect(
prefixCount(['pay', 'attention', 'practice', 'attend', 'at'], 'at')
).toEqual(3);
});
it('matches no word', () => {
expect(
prefixCount(['leetcode', 'win', 'loops', 'success'], 'code')
).toEqual(0);
});
});
================================================
FILE: coding_interviews/leetcode/easy/crawler-log-folder/crawler-log-folder.js
================================================
function minOperations(logs) {
let fileLevel = 0;
for (let log of logs) {
if (log === '../' && fileLevel) fileLevel--;
else if (log === '../') {
} else if (log === './') {
} else fileLevel++;
}
return Math.abs(fileLevel);
}
================================================
FILE: coding_interviews/leetcode/easy/create_target_array/create_target_array.py
================================================
# https://leetcode.com/problems/create-target-array-in-the-given-order/
def createTargetArray(nums, index):
target = []
for i in range(len(nums)):
target.insert(index[i], nums[i])
return target
================================================
FILE: coding_interviews/leetcode/easy/decode-the-message/decode-the-message.js
================================================
export function decodeMessage(key, message) {
let hashmap = new Map();
let alphabet = 'abcdefghijklmnopqrstuvwxyz';
let counter = 0;
hashmap.set(' ', ' ');
for (let char of key) {
if (!hashmap.has(char)) {
hashmap.set(char, alphabet[counter]);
counter++;
}
}
let result = [];
for (let char of message) {
result.push(hashmap.get(char));
}
return result.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/decode-the-message/tests/decode-the-message.test.js
================================================
import { describe, expect, it } from 'vitest';
import { decodeMessage } from '../decode-the-message';
describe('decodeMessage', () => {
it('', () => {
expect(
decodeMessage(
'eljuxhpwnyrdgtqkviszcfmabo',
'zwx hnfx lqantp mnoeius ycgk vcnjrdb'
)
).toEqual('the five boxing wizards jump quickly');
});
it('', () => {
expect(
decodeMessage(
'the quick brown fox jumps over the lazy dog',
'vkbs bs t suepuv'
)
).toEqual('this is a secret');
});
});
================================================
FILE: coding_interviews/leetcode/easy/decode_xored_array/decode_xored_array.py
================================================
# https://leetcode.com/problems/decode-xored-array
def decode(encoded, first):
original = [first]
for num in encoded:
original.append(original[-1] ^ num)
return original
================================================
FILE: coding_interviews/leetcode/easy/decompressed_encoded_list/decompressed_encoded_list.py
================================================
# https://leetcode.com/problems/decompress-run-length-encoded-list
'''
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Input: nums = [1,1,2,3]
Output: [1,3,3]
'''
def build_frequencies(frequency, num):
return [num for i in range(frequency)]
def decompress_list(nums):
result_list = []
for index in range(0, len(nums), 2):
result_list += build_frequencies(nums[index], nums[index+1])
return result_list
data_tests = [
([1, 2, 3, 4], [2, 4, 4, 4]),
([1, 1, 2, 3], [1, 3, 3])
]
for nums, expected in data_tests:
result = decompress_list(nums)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/decrypt_string/decrypt_string.py
================================================
# https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping
def alpha(num):
return chr(int(num) + ord('a') - 1)
def freqAlphabets(s):
result, index, s_length = [], 0, len(s)
while index < s_length:
if index + 2 < len(s) and s[index + 2] == '#':
result.append(alpha(s[index:index+2]))
index += 3
else:
result.append(alpha(s[index]))
index += 1
return ''.join(result)
================================================
FILE: coding_interviews/leetcode/easy/defanging_an_ip_address/defanging_an_ip_address.py
================================================
# https://leetcode.com/problems/defanging-an-ip-address/
'''
"1.1.1.1"
"1[.]1[.]1[.]1"
"255.100.50.0"
"255[.]100[.]50[.]0"
'''
def defang_ip_address(address):
address_chars_list = []
for char in address:
if char == '.':
address_chars_list.append('[.]')
else:
address_chars_list.append(char)
return ''.join(address_chars_list)
data_tests = [
("1.1.1.1", "1[.]1[.]1[.]1"),
("255.100.50.0", "255[.]100[.]50[.]0")
]
for address, expected in data_tests:
result = defang_ip_address(address)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/defuse-the-bomb/defuse-the-bomb.js
================================================
function sumNextK(code, from, k) {
let sum = 0;
for (let index = from + 1; index <= from + k; index++) {
sum += code[index];
}
return sum;
}
function decryptNext(code, k) {
let newCode = [...code, ...code];
let sum = sumNextK(newCode, 0, k);
let nextSum = [sum];
for (let index = 1; index < code.length; index++) {
sum = sum - newCode[index] + newCode[index + k];
nextSum.push(sum);
}
return nextSum;
}
function sumPreviousK(code, from, k) {
let sum = 0;
for (let index = from - 1; index >= from - k; index--) {
sum += code[index];
}
return sum;
}
function decryptPrevious(code, k) {
let newCode = [...code, ...code];
let sum = sumPreviousK(code, code.length - 1, k);
let previousSum = [sum];
for (let index = newCode.length - 2; index >= code.length; index--) {
sum = sum - newCode[index] + newCode[index - k];
previousSum.push(sum);
}
return previousSum.reverse();
}
function decryptWithZeros(code) {
return code.map((_) => 0);
}
function decrypt(code, k) {
if (k > 0) return decryptNext(code, k);
if (k < 0) return decryptPrevious(code, k * -1);
return decryptWithZeros(code);
}
================================================
FILE: coding_interviews/leetcode/easy/delete-greatest-value-in-each-row/delete-greatest-value-in-each-row.js
================================================
function isEmpty(grid) {
let lastRow = grid[grid.length - 1];
for (let col = 0; col < grid[0].length; col++) {
if (lastRow[col] !== 0) return false;
}
return true;
}
function deleteGreatestValue(grid) {
let result = 0;
while (!isEmpty(grid)) {
let max = -Infinity;
for (let row = 0; row < grid.length; row++) {
let maxCell = -Infinity;
let maxCol = -Infinity;
for (let col = 0; col < grid[row].length; col++) {
const cell = grid[row][col];
if (cell > maxCell) {
maxCell = Math.max(cell, maxCell);
maxCol = col;
}
}
max = Math.max(maxCell, max);
grid[row][maxCol] = 0;
}
result += max;
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/delete_columns_to_make_sorted/delete_columns_to_make_sorted.py
================================================
# https://leetcode.com/problems/delete-columns-to-make-sorted
def min_deletion_size(strs):
counter = 0
for col in range(len(strs[0])):
column = []
for row in range(len(strs)):
column.append(strs[row][col])
if column != sorted(column): counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/design-an-ordered-stream/design-an-ordered-stream.js
================================================
const OrderedStream = function (n) {
this.n = n;
this.key = 1;
this.hashmap = new Map();
};
OrderedStream.prototype.insert = function (idKey, value) {
this.hashmap.set(idKey, value);
if (this.key === idKey) {
const chunk = [];
for (let index = this.key; index <= this.n + 1; index++) {
if (this.hashmap.has(index)) {
const value = this.hashmap.get(index);
chunk.push(value);
this.hashmap.delete(index);
this.key++;
} else {
return chunk;
}
}
}
return [];
};
================================================
FILE: coding_interviews/leetcode/easy/design-hashmap/design-hashmap.js
================================================
const MyHashMap = function () {
this.map = [];
};
MyHashMap.prototype.put = function (key, value) {
let found = false;
this.map.forEach(([k], index) => {
if (key === k) {
this.map[index] = [key, value];
found = true;
}
});
if (!found) this.map.push([key, value]);
};
MyHashMap.prototype.get = function (key) {
let value = -1;
this.map.forEach(([k, v]) => {
if (key === k) {
value = v;
}
});
return value;
};
MyHashMap.prototype.remove = function (key) {
this.map.forEach(([k], index) => {
if (key === k) {
this.map = [...this.map.slice(0, index), ...this.map.slice(index + 1)];
}
});
};
================================================
FILE: coding_interviews/leetcode/easy/design-hashset/design-hashset.js
================================================
const MyHashSet = function () {
this.hashmap = new Map();
};
MyHashSet.prototype.add = function (key) {
this.hashmap.set(key, true);
};
MyHashSet.prototype.remove = function (key) {
this.hashmap.delete(key);
};
MyHashSet.prototype.contains = function (key) {
return this.hashmap.has(key);
};
================================================
FILE: coding_interviews/leetcode/easy/design_parking_system/design_parking_system.py
================================================
# https://leetcode.com/problems/design-parking-system
class ParkingSystem:
def __init__(self, big, medium, small):
self.big = big
self.medium = medium
self.small = small
def add_car(self, car_type):
if car_type == 1:
if self.big >= 1:
self.big -= 1
return True
else:
return False
if car_type == 2:
if self.medium >= 1:
self.medium -= 1
return True
else:
return False
if car_type == 3:
if self.small >= 1:
self.small -= 1
return True
else:
return False
================================================
FILE: coding_interviews/leetcode/easy/destination_city/destination_city.py
================================================
def dest_city(paths):
all_origins = []
all_destinations = []
for [city1, city2] in paths:
all_origins.append(city1)
all_destinations.append(city2)
return [d for d in all_destinations if d not in all_origins][0]
def dest_city(paths):
all_origins = set()
all_destinations = set()
for [city1, city2] in paths:
all_origins.add(city1)
all_destinations.add(city2)
return (all_destinations - all_origins).pop()
================================================
FILE: coding_interviews/leetcode/easy/detect-capital/detect-capital.js
================================================
function allCapitals(word) {
return word === word.toUpperCase();
}
function allNotCapitals(word) {
return word === word.toLowerCase();
}
function firstCapital(word) {
return allCapitals(word[0]) && allNotCapitals(word.slice(1));
}
function detectCapitalUse(word) {
return allCapitals(word) || allNotCapitals(word) || firstCapital(word);
}
================================================
FILE: coding_interviews/leetcode/easy/determine-if-string-halves-are-alike/determine-if-string-halves-are-alike.js
================================================
const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
function getVowelsCount(string) {
let count = 0;
for (let char of string) {
if (VOWELS.includes(char)) count++;
}
return count;
}
function halvesAreAlike(s) {
let halfIndex = s.length / 2;
let firstHalf = s.slice(0, halfIndex);
let secondHalf = s.slice(halfIndex);
let firstHalfVowelsCount = getVowelsCount(firstHalf);
let secondHalfVowelsCount = getVowelsCount(secondHalf);
return firstHalfVowelsCount === secondHalfVowelsCount;
}
================================================
FILE: coding_interviews/leetcode/easy/determine_color_of_a_chessboard_square/determine_color_of_a_chessboard_square.py
================================================
# https://leetcode.com/problems/determine-color-of-a-chessboard-square/
mapper = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8
}
def is_even(num):
return num % 2 == 0
def square_is_white(coordinates):
x, y = mapper[coordinates[0]], int(coordinates[1])
if x == y or (is_even(x - y)): return False
return True
def square_is_white(coordinates):
x, y = mapper[coordinates[0]], int(coordinates[1])
return not (x == y or (is_even(x - y)))
def square_is_white(coordinates):
return ord(coordinates[0]) % 2 != int(coordinates[1]) % 2
================================================
FILE: coding_interviews/leetcode/easy/di_string_match/di_string_match.py
================================================
# https://leetcode.com/problems/di-string-match
def di_string_match(S):
permutation, top, bottom = [], len(S), 0
for char in S:
if char == 'I':
permutation.append(bottom)
bottom += 1
else:
permutation.append(top)
top -= 1
permutation.append(top)
return permutation
================================================
FILE: coding_interviews/leetcode/easy/difference-between-element-sum-and-digit-sum-of-an-array/difference-between-element-sum-and-digit-sum-of-an-array.js
================================================
function getDigitsSum(num) {
let digits = 0;
let numString = num.toString();
for (let numChar of numString) {
digits += Number(numChar);
}
return digits;
}
function differenceOfSum(nums) {
let elementSum = 0;
let digitSum = 0;
for (let num of nums) {
elementSum += num;
digitSum += getDigitsSum(num);
}
return Math.abs(elementSum - digitSum);
}
================================================
FILE: coding_interviews/leetcode/easy/discount_price/discount_price.py
================================================
def finalPrices(prices):
result = []
for index, price in enumerate(prices):
discount = get_discount(prices, index, price)
result.append(price - discount)
return result
def get_discount(prices, index, price):
for other_price in prices[index + 1:]:
if other_price <= price:
return other_price
return 0
================================================
FILE: coding_interviews/leetcode/easy/distribute-candies-among-children-i/distribute-candies-among-children-i.js
================================================
// https://leetcode.com/problems/distribute-candies-among-children-i
function distributeCandies(n, limit) {
let count = 0;
for (let i = limit; i >= 0; i--) {
for (let j = limit; j >= 0; j--) {
for (let k = limit; k >= 0; k--) {
if (i + j + k === n) {
count++;
}
}
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/distribute-candies-among-children-i/distribute-candies-among-children-ii.js
================================================
// https://leetcode.com/problems/distribute-candies-among-children-i
function distributeCandies(n, limit) {
let count = 0;
for (let i = limit; i >= 0; i--) {
for (let j = limit; j >= 0; j--) {
let k = n - i - j;
if (k >= 0 && k <= limit) {
count++;
}
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/distribute-candies-to-people/distribute-candies-to-people.js
================================================
function initPeopleCandies(numPeople) {
let peopleCandies = [];
for (let i = 0; i < numPeople; i++) {
peopleCandies.push(0);
}
return peopleCandies;
}
function distributeCandies(candies, numPeople) {
let peopleCandies = initPeopleCandies(numPeople);
let numOfCandies = 1;
let index = 0;
while (candies) {
let candiesToAssign = numOfCandies > candies ? candies : numOfCandies;
peopleCandies[index] += candiesToAssign;
candies -= candiesToAssign;
numOfCandies++;
index = (index + 1) % numPeople;
}
return peopleCandies;
}
================================================
FILE: coding_interviews/leetcode/easy/divide-a-string-into-groups-of-size-k/divide-a-string-into-groups-of-size-k.js
================================================
function fillChar(lastGroup, fill, length) {
let chars = [];
for (let i = 1; i <= length; i++) {
chars.push(fill);
}
return lastGroup + chars.join('');
}
function divideString(s, k, fill) {
let groups = [];
let groupSize = 0;
let group = [];
for (let index = 0; index < s.length; index++) {
group.push(s[index]);
groupSize++;
if (groupSize === k) {
groups.push(group.join(''));
groupSize = 0;
group = [];
} else if (index === s.length - 1) {
groups.push(group.join(''));
}
}
let lastGroup = groups[groups.length - 1];
let lastGroupLength = lastGroup.length;
if (lastGroupLength !== k) {
lastGroup = fillChar(lastGroup, fill, k - lastGroupLength);
groups[groups.length - 1] = lastGroup;
}
return groups;
}
================================================
FILE: coding_interviews/leetcode/easy/divide-array-into-equal-pairs/divide-array-into-equal-pairs.js
================================================
export function divideArray(nums) {
const map = {};
for (let num of nums) {
if (map[num]) {
map[num] += 1;
} else {
map[num] = 1;
}
}
let hasEqualPairs = true;
for (let num of Object.values(map)) {
if (num % 2 !== 0) {
hasEqualPairs = false;
break;
}
}
return hasEqualPairs;
}
================================================
FILE: coding_interviews/leetcode/easy/divide-array-into-equal-pairs/tests/divide-array-into-equal-pairs.test.js
================================================
import { describe, expect, it } from 'vitest';
import { divideArray } from '../divide-array-into-equal-pairs';
describe('divideArray', () => {
it('', () => {
expect(divideArray([3, 2, 3, 2, 2, 2])).toEqual(true);
});
it('', () => {
expect(divideArray([1, 2, 3, 4])).toEqual(false);
});
it('', () => {
expect(divideArray([2, 2])).toEqual(true);
});
});
================================================
FILE: coding_interviews/leetcode/easy/divisible-and-non-divisible-sums-difference/divisible-and-non-divisible-sums-difference.js
================================================
// https://leetcode.com/problems/divisible-and-non-divisible-sums-difference
function differenceOfSums(n, m) {
let num1 = 0,
num2 = 0;
for (let num = 1; num <= n; num++) {
if (num % m === 0) num2 += num;
else num1 += num;
}
return num1 - num2;
}
================================================
FILE: coding_interviews/leetcode/easy/divisor-game/divisor-game.js
================================================
// https://leetcode.com/problems/divisor-game
function divisorGame(n) {
return n % 2 === 0;
}
================================================
FILE: coding_interviews/leetcode/easy/equal_reversed_arrays/equal_reversed_arrays.py
================================================
# https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays
'''
Given two integer arrays of equal length target and arr.
In one step, you can select any non-empty sub-array of arr and reverse it.
You are allowed to make any number of steps.
Return True if you can make arr equal to target, or False otherwise.
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Input: target = [7], arr = [7]
Output: true
Input: target = [1,12], arr = [12,1]
Output: true
'''
# 0(nlogn)
def can_be_equal(target, arr):
return target == arr or sorted(target) == sorted(arr)
# 0(n)
def can_be_equal(target, arr):
counter = {}
for index in range(len(target)):
target_item, arr_item = target[index], arr[index]
if target_item in counter:
counter[target_item] += 1
else:
counter[target_item] = 1
if arr_item in counter:
counter[arr_item] += 1
else:
counter[arr_item] = 1
for _, value in counter.items():
if value % 2 != 0:
return False
return True
def can_be_equal(target, arr):
return collections.Counter(target) == collections.Counter(arr)
================================================
FILE: coding_interviews/leetcode/easy/evaluate-boolean-binary-tree/evaluate-boolean-binary-tree.js
================================================
const values = {
or: 2,
and: 3,
};
function evaluateTree(root) {
if ([0, 1].includes(root.val)) return Boolean(root.val);
const left = evaluateTree(root.left);
const right = evaluateTree(root.right);
return root.val === values.or ? left || right : left && right;
}
================================================
FILE: coding_interviews/leetcode/easy/even_digits/even_digits.py
================================================
# https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
def find_numbers(nums):
counter = 0
for num in nums:
if len(str(num)) % 2 == 0:
counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/excel-sheet-column-number/excel-sheet-column-number.js
================================================
function toNumber(char) {
return char.charCodeAt(0) - 64;
}
function titleToNumber(columnTitle) {
let columnNumber = 0;
for (let col of columnTitle) {
const num = toNumber(col);
columnNumber = columnNumber * 26 + num;
}
return columnNumber;
}
================================================
FILE: coding_interviews/leetcode/easy/fair-candy-swap/fair-candy-swap-optimized.js
================================================
function sum(nums) {
let sumOfNums = 0;
for (let num of nums) {
sumOfNums += num;
}
return sumOfNums;
}
function buildMap(bobSizes) {
let hashmap = new Map();
for (let bobSize of bobSizes) {
hashmap.set(bobSize, bobSize);
}
return hashmap;
}
function fairCandySwap(aliceSizes, bobSizes) {
let aliceCandies = sum(aliceSizes);
let bobCandies = sum(bobSizes);
let hashmap = buildMap(bobSizes);
for (let aliceSize of aliceSizes) {
let bobCandy = (bobCandies + 2 * aliceSize - aliceCandies) / 2;
if (hashmap.has(bobCandy)) {
return [aliceSize, bobCandy];
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/fair-candy-swap/fair-candy-swap.js
================================================
function sum(nums) {
let sumOfNums = 0;
for (let num of nums) {
sumOfNums += num;
}
return sumOfNums;
}
function fairCandySwap(aliceSizes, bobSizes) {
let aliceCandies = sum(aliceSizes);
let bobCandies = sum(bobSizes);
for (let i = 0; i < aliceSizes.length; i++) {
for (let j = 0; j < bobSizes.length; j++) {
let aliceCandy = aliceSizes[i];
let bobCandy = bobSizes[j];
if (
aliceCandies - aliceCandy + bobCandy ===
bobCandies - bobCandy + aliceCandy
) {
return [aliceCandy, bobCandy];
}
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/faulty-keyboard/faulty-keyboard.js
================================================
// https://leetcode.com/problems/faulty-keyboard
function reverse(s) {
let reversedS = [];
for (let index = s.length - 1; index >= 0; index--) {
reversedS.push(s[index]);
}
return reversedS;
}
function finalString(s) {
let subS = [];
for (let char of s) {
if (char === 'i') subS = reverse(subS);
else subS.push(char);
}
return subS.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/fibonacci_number/fibonacci_number.py
================================================
# https://leetcode.com/problems/fibonacci-number
def fib(n):
cache = [0, 1]
prev_1, prev_2 = 0, 1
if n == 0: return 0
if n == 1: return 1
for _ in range(2, n + 1):
cache.append(cache[prev_1] + cache[prev_2])
prev_1 += 1
prev_2 += 1
return cache[-1]
================================================
FILE: coding_interviews/leetcode/easy/final-value-after-operations/final-value-after-operations.js
================================================
/*
There is a programming language with only four operations and one variable X:
++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
# Example 1
Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
# Example 2
Input: operations = ["++X","++X","X++"]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.
# Example 3
Input: operations = ["X++","++X","--X","X--"]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.
*/
const operationsMap = {
'--X': -1,
'X--': -1,
'++X': +1,
'X++': +1,
};
function finalValueAfterOperations(operations = []) {
let x = 0;
operations.forEach((operation) => {
x += operationsMap[operation];
});
return x;
}
console.log(finalValueAfterOperations(['--X', 'X++', 'X++']), 1);
console.log(finalValueAfterOperations(['++X', '++X', 'X++']), 3);
console.log(finalValueAfterOperations(['X++', '++X', '--X', 'X--']), 0);
================================================
FILE: coding_interviews/leetcode/easy/find-all-k-distant-indices-in-an-array/find-all-k-distant-indices-in-an-array.js
================================================
function getJs(nums, key) {
let js = [];
for (let index = 0; index < nums.length; index++) {
if (nums[index] === key) js.push(index);
}
return js;
}
function isKDistant(index, js, k) {
for (let j of js) {
if (Math.abs(index - j) <= k) return true;
}
return false;
}
function findKDistantIndices(nums, key, k) {
const js = getJs(nums, key);
const output = [];
console.log('js', js);
for (let index = 0; index < nums.length; index++) {
if (isKDistant(index, js, k)) {
output.push(index);
}
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.js
================================================
function buildMap(nums) {
let hashmap = new Map();
for (let num of nums) {
hashmap.set(num, true);
}
return hashmap;
}
function findDisappearedNumbers(nums) {
let hashmap = buildMap(nums);
let output = [];
for (let num = 1; num <= nums.length; num++) {
if (!hashmap.has(num)) output.push(num);
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/find-center-of-star-graph/find-center-of-star-graph.js
================================================
function addConnection(nodeToConnectionsCount, node) {
if (nodeToConnectionsCount[node]) {
nodeToConnectionsCount[node]++;
} else {
nodeToConnectionsCount[node] = 1;
}
}
function findCenter(edges) {
let nodeToConnectionsCount = {};
for (let [first, second] of edges) {
addConnection(nodeToConnectionsCount, first);
addConnection(nodeToConnectionsCount, second);
}
let star;
let maxConnections = -Infinity;
Object.entries(nodeToConnectionsCount).forEach(([node, count]) => {
if (count > maxConnections) {
star = node;
maxConnections = count;
}
});
return star;
}
================================================
FILE: coding_interviews/leetcode/easy/find-champion-i/find-champion-i-no-map.js
================================================
// https://leetcode.com/problems/find-champion-i
function findChampion(grid) {
for (let i = 0; i < grid.length; i++) {
let count = 0;
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === 1) {
count++;
}
}
if (count === grid.length - 1) {
return i;
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/find-champion-i/find-champion-i.js
================================================
// https://leetcode.com/problems/find-champion-i
function findChampion(grid) {
let winners = new Map();
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if (grid[i][j] === 1) {
winners.set(i, (winners.get(i) || 0) + 1);
}
}
}
for (let [key, value] of winners.entries()) {
if (value === grid.length - 1) {
return key;
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/find-first-palindromic-string-in-the-array/find-first-palindromic-string-in-the-array.js
================================================
export function isPalindrome(word) {
for (let i = 0; i < Math.floor(word.length / 2); i++) {
if (word[i] !== word[word.length - 1 - i]) {
return false;
}
}
return true;
}
export function firstPalindrome(words) {
let palindromicWord = '';
for (let i = 0; i < words.length; i++) {
if (isPalindrome(words[i])) {
palindromicWord = words[i];
break;
}
}
return palindromicWord;
}
================================================
FILE: coding_interviews/leetcode/easy/find-first-palindromic-string-in-the-array/tests/find-first-palindromic-string-in-the-array.test.js
================================================
import { describe, expect, it } from 'vitest';
import {
firstPalindrome,
isPalindrome,
} from '../find-first-palindromic-string-in-the-array';
describe('firstPalindrome', () => {
it('', () => {
expect(firstPalindrome(['abc', 'car', 'ada', 'racecar', 'cool'])).toEqual(
'ada'
);
});
it('', () => {
expect(firstPalindrome(['notapalindrome', 'racecar'])).toEqual('racecar');
});
it('', () => {
expect(firstPalindrome(['def', 'ghi'])).toEqual('');
});
});
describe('isPalindrome', () => {
it('', () => {
expect(isPalindrome('ada')).toBeTruthy();
});
it('', () => {
expect(isPalindrome('')).toBeTruthy();
});
it('', () => {
expect(isPalindrome('eda')).toBeFalsy();
});
});
================================================
FILE: coding_interviews/leetcode/easy/find-greatest-common-divisor-of-array/find-greatest-common-divisor-of-array.js
================================================
// https://leetcode.com/problems/find-greatest-common-divisor-of-array
const findSmallestAndLargest = (nums) => {
let smallest = Infinity;
let largest = -Infinity;
for (let i = 0; i < nums.length; i++) {
smallest = Math.min(smallest, nums[i]);
largest = Math.max(largest, nums[i]);
}
return [smallest, largest];
};
const gcd = (num1, num2) => (num2 ? gcd(num2, num1 % num2) : num1);
const findGCD = (nums) => {
const [smallest, largest] = findSmallestAndLargest(nums);
return gcd(smallest, largest);
};
================================================
FILE: coding_interviews/leetcode/easy/find-indices-with-index-and-value-difference-i/find-indices-with-index-and-value-difference-i.js
================================================
// https://leetcode.com/problems/find-indices-with-index-and-value-difference-i
function findIndices(nums, indexDifference, valueDifference) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (
Math.abs(i - j) >= indexDifference &&
Math.abs(nums[i] - nums[j]) >= valueDifference
) {
return [i, j];
}
}
}
return [-1, -1];
}
================================================
FILE: coding_interviews/leetcode/easy/find-lucky-integer-in-an-array/find-lucky-integer-in-an-array.js
================================================
function buildNumCounter(nums) {
let counter = new Map();
for (let num of nums) {
if (counter.has(num)) counter.set(num, counter.get(num) + 1);
else counter.set(num, 1);
}
return counter;
}
function findLucky(nums) {
let largestLuckyInteger = -1;
let counter = buildNumCounter(nums);
for (let num of nums) {
if (num === counter.get(num) && num > largestLuckyInteger) {
largestLuckyInteger = num;
}
}
return largestLuckyInteger;
}
================================================
FILE: coding_interviews/leetcode/easy/find-maximum-number-of-string-pairs/find-maximum-number-of-string-pairs.js
================================================
// https://leetcode.com/problems/find-maximum-number-of-string-pairs
function paired(s1, s2) {
for (let i = 0; i < s1.length; i++) {
if (s1[i] !== s2[s2.length - 1 - i]) {
return false;
}
}
return true;
}
function maximumNumberOfStringPairs(words) {
let max = 0;
for (let i = 0; i < words.length - 1; i++) {
for (let j = i + 1; j < words.length; j++) {
if (paired(words[i], words[j])) {
max++;
}
}
}
return max;
}
================================================
FILE: coding_interviews/leetcode/easy/find-nearest-point-that-has-the-same-x-or-y-coordinate/find-nearest-point-that-has-the-same-x-or-y-coordinate.js
================================================
// https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate
// points = [] - not empty
// x and y positive numbers
const nearestValidPoint = (x, y, points) => {
let minDistance = Infinity;
let pointIndex = -1;
points.forEach((point, index) => {
if (isValid([x, y], point)) {
const manhattanDistance = calculateManhattanDistance([x, y], point);
if (manhattanDistance < minDistance) {
pointIndex = index;
minDistance = manhattanDistance;
}
}
});
return pointIndex;
};
const isValid = (position, point) => {
const [x, y] = position;
const [pointX, pointY] = point;
return x === pointX || y === pointY;
};
const calculateManhattanDistance = (position, point) => {
const [x, y] = position;
const [pointX, pointY] = point;
return Math.abs(x - pointX) + Math.abs(y - pointY);
};
================================================
FILE: coding_interviews/leetcode/easy/find-subarrays-with-equal-sum/find-subarrays-with-equal-sum.js
================================================
function findSubarrays(nums) {
for (let i = 0; i < nums.length - 2; i++) {
for (let j = i + 1; j < nums.length - 1; j++) {
if (nums[i] + nums[i + 1] === nums[j] + nums[j + 1]) return true;
}
}
return false;
}
================================================
FILE: coding_interviews/leetcode/easy/find-target-indices-after-sorting-array/find-target-indices-after-sorting-array.js
================================================
export function targetIndices(nums, target) {
const sortedNums = nums.sort((num1, num2) => num1 - num2);
const result = [];
sortedNums.forEach((num, index) => {
if (num === target) {
result.push(index);
}
});
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/find-target-indices-after-sorting-array/tests/find-target-indices-after-sorting-array.test.js
================================================
import { describe, expect, it } from 'vitest';
import { targetIndices } from '../find-target-indices-after-sorting-array';
describe('targetIndices', () => {
it('', () => {
expect(
targetIndices(
[
48, 90, 9, 21, 31, 35, 19, 69, 29, 52, 100, 54, 21, 86, 6, 45, 42, 5,
62, 77, 15, 38,
],
6
)
).toEqual([1]);
});
it('', () => {
expect(targetIndices([1, 2, 5, 2, 3], 2)).toEqual([1, 2]);
});
it('', () => {
expect(targetIndices([1, 2, 5, 2, 3], 3)).toEqual([3]);
});
it('', () => {
expect(targetIndices([1, 2, 5, 2, 3], 5)).toEqual([4]);
});
});
================================================
FILE: coding_interviews/leetcode/easy/find-the-array-concatenation-value/find-the-array-concatenation-value.js
================================================
function concat(num1, num2) {
return Number(num1.toString() + num2.toString());
}
function findTheArrayConcVal(nums) {
let pointer1 = 0;
let pointer2 = nums.length - 1;
let output = 0;
while (pointer1 <= pointer2) {
if (pointer1 === pointer2) output += nums[pointer1];
else output += concat(nums[pointer1], nums[pointer2]);
pointer1++;
pointer2--;
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-difference/find-the-difference.js
================================================
function buildMap(string) {
let hashmap = new Map();
for (let char of string) {
if (hashmap.has(char)) hashmap.set(char, hashmap.get(char) + 1);
else hashmap.set(char, 1);
}
return hashmap;
}
function findTheDifference(s, t) {
let hashmap = buildMap(s);
for (let char of t) {
if (hashmap.has(char) && hashmap.get(char) > 0) {
hashmap.set(char, hashmap.get(char) - 1);
continue;
}
return char;
}
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-difference-of-two-arrays/find-the-difference-of-two-arrays.js
================================================
function buildHashmap(nums) {
let hashmap = new Map();
for (let num of nums) {
hashmap.set(num, true);
}
return hashmap;
}
function buildDistinct(nums, hashmap) {
let distinct = [];
for (let num of nums) {
if (!hashmap.has(num)) {
distinct.push(num);
hashmap.set(num, true);
}
}
return distinct;
}
function findDifference(nums1, nums2) {
let hashmap1 = buildHashmap(nums1);
let hashmap2 = buildHashmap(nums2);
let distinct1 = buildDistinct(nums1, hashmap2);
let distinct2 = buildDistinct(nums2, hashmap1);
return [distinct1, distinct2];
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-distance-value-between-two-arrays/find-the-distance-value-between-two-arrays.js
================================================
// https://leetcode.com/problems/find-the-distance-value-between-two-arrays
function hasSmallerValue(num, arr, d) {
for (let number of arr) {
if (Math.abs(num - number) <= d) return true;
}
return false;
}
function findTheDistanceValue(arr1, arr2, d) {
let count = 0;
for (let num1 of arr1) {
if (!hasSmallerValue(num1, arr2, d)) count++;
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-distinct-difference-array/find-the-distinct-difference-array.js
================================================
// https://leetcode.com/problems/find-the-distinct-difference-array
function countDistinct(nums, startIndex, endIndex) {
let count = 0;
let distinct = new Map();
for (let i = startIndex; i <= endIndex; i++) {
if (!distinct.has(nums[i])) {
distinct.set(nums[i], nums[i]);
count++;
}
}
return count;
}
function countDistinctPrefix(nums, index) {
return countDistinct(nums, 0, index);
}
function countDistinctSufix(nums, index) {
return countDistinct(nums, index + 1, nums.length - 1);
}
function distinctDifferenceArray(nums) {
let diff = [];
for (let index = 0; index < nums.length; index++) {
let prefix = countDistinctPrefix(nums, index);
let sufix = countDistinctSufix(nums, index);
diff.push(prefix - sufix);
}
return diff;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-distinct-difference-array/optimized-find-the-distinct-difference-array.js
================================================
// https://leetcode.com/problems/find-the-distinct-difference-array
function distinctDifferenceArray(nums) {
let distinctDiff = [];
let countInLeft = 0;
let countInRight = 0;
let leftCounterMap = new Map();
let rightCounterMap = new Map();
for (let num of nums) {
if (leftCounterMap.has(num)) {
leftCounterMap.set(num, leftCounterMap.get(num) + 1);
} else {
leftCounterMap.set(num, 1);
countInLeft++;
}
}
distinctDiff.unshift(countInLeft - countInRight);
for (let index = nums.length - 1; index > 0; index--) {
let num = nums[index];
leftCounterMap.set(num, leftCounterMap.get(num) - 1);
if (leftCounterMap.get(num) === 0) countInLeft--;
rightCounterMap.set(num, (rightCounterMap.get(num) || 0) + 1);
if (rightCounterMap.get(num) === 1) countInRight++;
distinctDiff.unshift(countInLeft - countInRight);
}
return distinctDiff;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-maximum-achievable-number/find-the-maximum-achievable-number.js
================================================
// https://leetcode.com/problems/find-the-maximum-achievable-number
function theMaximumAchievableX(num, t) {
return t * 2 + num;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-middle-index-in-array/find-the-middle-index-in-array.js
================================================
function sum(nums) {
return nums.reduce((sumOfNums, num) => sumOfNums + num, 0);
}
function findMiddleIndex(nums) {
let sumOfNums = sum(nums) - nums[0];
let firstHalfSum = 0;
let index = 0;
while (index < nums.length - 1 && sumOfNums !== firstHalfSum) {
sumOfNums -= nums[index + 1];
firstHalfSum += nums[index];
index++;
}
return sumOfNums === firstHalfSum ? index : -1;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-pivot-integer/find-the-pivot-integer.js
================================================
const NO_PIVOT = -1;
function sum(n) {
let sumOfNs = 0;
for (let num = 1; num <= n; num++) {
sumOfNs += num;
}
return sumOfNs;
}
function pivotInteger(n) {
let sumOfNs = sum(n);
let leftSum = 0;
for (let num = 1; num <= n; num++) {
leftSum += num;
if (sumOfNs === leftSum) return num;
sumOfNs -= num;
}
return NO_PIVOT;
}
================================================
FILE: coding_interviews/leetcode/easy/find-the-width-of-columns-of-a-grid/find-the-width-of-columns-of-a-grid.js
================================================
// https://leetcode.com/problems/find-the-width-of-columns-of-a-grid
function findColumnWidth(grid) {
let output = [];
for (let col = 0; col < grid[0].length; col++) {
let max = -Infinity;
for (let row = 0; row < grid.length; row++) {
let cell = grid[row][col];
let length = cell.toString().length;
max = Math.max(max, length);
}
output.push(max);
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/find-words-containing-character/find-words-containing-character.js
================================================
// https://leetcode.com/problems/find-words-containing-character
function findWordsContaining(words, x) {
let indices = [];
for (let index = 0; index < words.length; index++) {
for (let char of words[index]) {
if (char === x) {
indices.push(index);
break;
}
}
}
return indices;
}
================================================
FILE: coding_interviews/leetcode/easy/find-words-that-can-be-formed-by-characters/find-words-that-can-be-formed-by-characters.js
================================================
function buildCounter(chars) {
let counter = new Map();
for (let char of chars) {
if (counter.has(char)) counter.set(char, counter.get(char) + 1);
else counter.set(char, 1);
}
return counter;
}
function isGood(word, counterCopy) {
for (let char of word) {
if (counterCopy.has(char) && counterCopy.get(char) > 0)
counterCopy.set(char, counterCopy.get(char) - 1);
else return false;
}
return true;
}
function countCharacters(words, chars) {
let counter = buildCounter(chars);
let counterCopy;
let goodWords = [];
for (let word of words) {
counterCopy = new Map(counter);
if (isGood(word, counterCopy)) goodWords.push(word);
}
return goodWords.reduce((lengths, word) => lengths + word.length, 0);
}
================================================
FILE: coding_interviews/leetcode/easy/find_common_characters/find_common_characters.py
================================================
# https://leetcode.com/problems/find-common-characters
def common_chars(A):
if len(A) == 1: return [char for char in A]
word = A[0]
words = A[1:]
result = []
for char in word:
all = True
for index, other_word in enumerate(words):
if char in other_word:
other_word_index = other_word.index(char)
words[index] = words[index][:other_word_index] + words[index][other_word_index+1:]
else:
all = False
break
if all: result.append(char)
return result
================================================
FILE: coding_interviews/leetcode/easy/find_the_highest_altitude/find_the_highest_altitude.py
================================================
# https://leetcode.com/problems/find-the-highest-altitude
def largest_altitude(gain):
highest_altitude, current_altitude = 0, 0
for net_gain in gain:
current_altitude += net_gain
if current_altitude > highest_altitude:
highest_altitude = current_altitude
return highest_altitude
================================================
FILE: coding_interviews/leetcode/easy/first-bad-version/first-bad-version-binary-search.js
================================================
function getMiddle(start, end) {
return Math.floor((start + end) / 2);
}
function binarySearchFirstBadVersion(isBadVersion) {
return (n) => {
let start = 1;
let end = n;
let middle = getMiddle(start, end);
let firstBadVersion = middle;
while (start < end) {
if (isBadVersion(middle)) {
end = middle - 1;
} else {
start = middle + 1;
}
middle = getMiddle(start, end);
if (isBadVersion(middle)) {
firstBadVersion = middle;
}
}
return firstBadVersion;
};
}
function solution(isBadVersion) {
return binarySearchFirstBadVersion(isBadVersion);
}
================================================
FILE: coding_interviews/leetcode/easy/first-bad-version/first-bad-version.js
================================================
function solution(isBadVersion) {
return function (n) {
for (let version = 1; version <= n; version++) {
if (isBadVersion(version)) {
return version;
}
}
};
}
================================================
FILE: coding_interviews/leetcode/easy/first-letter-to-appear-twice/first-letter-to-appear-twice.js
================================================
function repeatedCharacter(s) {
let counter = new Map();
for (let char of s) {
if (counter.has(char)) {
return char;
}
counter.set(char, 1);
}
}
================================================
FILE: coding_interviews/leetcode/easy/first-unique-character-in-a-string/first-unique-character-in-a-string.js
================================================
function firstUniqChar(s) {
let charCount = {};
for (let char of s) {
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
for (let index = 0; index < s.length; index++) {
if (charCount[s[index]] === 1) {
return index;
}
}
return -1;
}
================================================
FILE: coding_interviews/leetcode/easy/first_bad_version/first_bad_version.py
================================================
'''
Approach #1 (Linear Scan) [Time Limit Exceeded]
The straight forward way is to brute force it by doing a linear scan.
Complexity analysis
Time complexity : O(n)O(n). Assume that isBadVersion(version)isBadVersion(version) takes constant time to check if a version is bad. It takes at most n - 1n−1 checks, therefore the overall time complexity is O(n)O(n).
Space complexity : O(1)O(1).
Approach #2 (Binary Search) [Accepted]
It is not difficult to see that this could be solved using a classic algorithm - Binary search. Let us see how the search space could be halved each time below.
Scenario #1: isBadVersion(mid) => false
1 2 3 4 5 6 7 8 9
G G G G G G B B B G = Good, B = Bad
| | |
left mid right
Let us look at the first scenario above where isBadVersion(mid) \Rightarrow falseisBadVersion(mid)⇒false. We know that all versions preceding and including midmid are all good. So we set left = mid + 1left=mid+1 to indicate that the new search space is the interval [mid + 1, right][mid+1,right] (inclusive).
Scenario #2: isBadVersion(mid) => true
1 2 3 4 5 6 7 8 9
G G G B B B B B B G = Good, B = Bad
| | |
left mid right
The only scenario left is where isBadVersion(mid) \Rightarrow trueisBadVersion(mid)⇒true. This tells us that midmid may or may not be the first bad version, but we can tell for sure that all versions after midmid can be discarded. Therefore we set right = midright=mid as the new search space of interval [left,mid][left,mid] (inclusive).
In our case, we indicate leftleft and rightright as the boundary of our search space (both inclusive). This is why we initialize left = 1left=1 and right = nright=n. How about the terminating condition? We could guess that leftleft and rightright eventually both meet and it must be the first bad version, but how could you tell for sure?
The formal way is to prove by induction, which you can read up yourself if you are interested. Here is a helpful tip to quickly prove the correctness of your binary search algorithm during an interview. We just need to test an input of size 2. Check if it reduces the search space to a single element (which must be the answer) for both of the scenarios above. If not, your algorithm will never terminate.
If you are setting mid = \frac{left + right}{2}mid=
2
left+right
, you have to be very careful. Unless you are using a language that does not overflow such as Python, left + rightleft+right could overflow. One way to fix this is to use left + \frac{right - left}{2}left+
2
right−left
instead.
If you fall into this subtle overflow bug, you are not alone. Even Jon Bentley's own implementation of binary search had this overflow bug and remained undetected for over twenty years.
Complexity analysis
Time complexity : O(logn). The search space is halved each time, so the time complexity is O(\log n)O(logn).
Space complexity : O(1).
'''
def is_bad_version(version):
True
def first_bad_version(n):
start = 1
last = n
while start < last:
middle = (start + last) / 2
if is_bad_version(middle):
last = middle
else:
start = middle + 1
return start
================================================
FILE: coding_interviews/leetcode/easy/fizz-buzz/fizz-buzz.js
================================================
function fizzBuzz(n) {
const answer = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
answer.push('FizzBuzz');
continue;
}
if (i % 3 === 0) {
answer.push('Fizz');
continue;
}
if (i % 5 === 0) {
answer.push('Buzz');
continue;
}
answer.push(String(i));
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/easy/flipping_an_image.py
================================================
# https://leetcode.com/problems/flipping-an-image/description/
# input: [[1,1,0], [1,0,1], [0,0,0]]
# output: [[1,0,0], [0,1,0], [1,1,1]]
def flip_and_invert_image(image):
for i in range(len(image)):
image[i] = image[i][::-1]
for i in range(len(image)):
for j in range(len(image[i])):
image[i][j] = 1 - image[i][j]
return image
print(flip_and_invert_image([[1,1,0], [1,0,1], [0,0,0]]))
================================================
FILE: coding_interviews/leetcode/easy/flood-fill/flood-fill-without-visited.js
================================================
function isInsideTheGrid(image, row, col) {
const validRow = row >= 0 && row < image.length;
const validCol = col >= 0 && col < image[0].length;
return validRow && validCol;
}
function dfs(image, row, col, newColor, startingPixel) {
if (isInsideTheGrid(image, row, col) && image[row][col] === startingPixel) {
image[row][col] = newColor;
dfs(image, row - 1, col, newColor, startingPixel);
dfs(image, row, col + 1, newColor, startingPixel);
dfs(image, row, col - 1, newColor, startingPixel);
dfs(image, row + 1, col, newColor, startingPixel);
}
}
function floodFill(image, row, col, newColor) {
if (image[row][col] !== newColor) {
dfs(image, row, col, newColor, image[row][col]);
}
return image;
}
================================================
FILE: coding_interviews/leetcode/easy/flood-fill/flood-fill.js
================================================
/**
- is it inside the grid?
- is it equal to the target value?
- update the pixe with newColor
- recursive call for: top, left, right, bottom
*/
function isInsideTheGrid(image, row, col) {
const validRow = row >= 0 && row < image.length;
const validCol = col >= 0 && col < image[0].length;
return validRow && validCol;
}
function floodFillHelper(image, sr, sc, newColor, startingPixel, visited) {
if (isInsideTheGrid(image, sr, sc)) {
let currentPixel = image[sr][sc];
if (currentPixel === startingPixel && !visited[sr][sc]) {
image[sr][sc] = newColor;
visited[sr][sc] = true;
let topPosition = {
row: sr - 1,
col: sc,
};
let rightPosition = {
row: sr,
col: sc + 1,
};
let leftPosition = {
row: sr,
col: sc - 1,
};
let bottomPosition = {
row: sr + 1,
col: sc,
};
floodFillHelper(
image,
topPosition.row,
topPosition.col,
newColor,
startingPixel,
visited
);
floodFillHelper(
image,
rightPosition.row,
rightPosition.col,
newColor,
startingPixel,
visited
);
floodFillHelper(
image,
leftPosition.row,
leftPosition.col,
newColor,
startingPixel,
visited
);
floodFillHelper(
image,
bottomPosition.row,
bottomPosition.col,
newColor,
startingPixel,
visited
);
}
}
}
function buildVisitedMatrix(image) {
let matrix = [];
for (let row = 0; row < image.length; row++) {
let r = [];
for (let col = 0; col < image[row].length; col++) {
r.push(false);
}
matrix.push(r);
}
return matrix;
}
function floodFill(image, sr, sc, newColor) {
let visited = buildVisitedMatrix(image);
floodFillHelper(image, sr, sc, newColor, image[sr][sc], visited);
return image;
}
================================================
FILE: coding_interviews/leetcode/easy/furthest-point-from-origin/furthest-point-from-origin.js
================================================
// https://leetcode.com/problems/furthest-point-from-origin
function furthestDistanceFromOrigin(moves) {
let diff = 0;
let underlines = 0;
for (let move of moves) {
if (move === '_') underlines++;
if (move === 'R') diff++;
if (move === 'L') diff--;
}
return Math.abs(diff) + underlines;
}
================================================
FILE: coding_interviews/leetcode/easy/generate_the_string/generate_the_string.py
================================================
# https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts
def generate_the_string(n):
if n % 2 == 0:
return 'a' * (n - 1) + 'b'
return 'a' * n
================================================
FILE: coding_interviews/leetcode/easy/goal_parser_interpretation/goal_parser_interpretation.py
================================================
# https://leetcode.com/problems/goal-parser-interpretation
def interpret(command):
result, empty_paren = [], True
for char in command:
if char == 'G':
result.append('G')
else:
if char == ')':
if empty_paren:
result.append('o')
else:
result.append('al')
empty_paren = True
elif char != '(':
empty_paren = False
return ''.join(result)
================================================
FILE: coding_interviews/leetcode/easy/greatest-english-letter-in-upper-and-lower-case/greatest-english-letter-in-upper-and-lower-case.js
================================================
function greatestLetter(string) {
let greatest = [-Infinity, ''];
let charsToCode = new Map();
for (let char of string) {
let lowerCasedChar = char.toLowerCase();
let charCode = char.charCodeAt();
if (
charsToCode.has(lowerCasedChar) &&
charsToCode.get(lowerCasedChar) !== charCode
) {
const greaterCharCode = Math.max(
charCode,
charsToCode.get(lowerCasedChar)
);
greatest =
greaterCharCode > greatest[0]
? [greaterCharCode, char.toUpperCase()]
: greatest;
} else if (!charsToCode.has(lowerCasedChar)) {
charsToCode.set(lowerCasedChar, charCode);
}
}
return greatest[1];
}
================================================
FILE: coding_interviews/leetcode/easy/greatest_candies/greatest_candies.py
================================================
# https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
'''
[2, 3, 3, 1, 3] 2
[True, True, True, True, True]
'''
def kids_with_candies(candies, extra_candies):
greatest = get_greatest(candies)
return map_can_be_greatest(candies, extra_candies, greatest)
def map_can_be_greatest(candies, extra_candies, greatest_candy):
greatest_possibilities = []
for candy in candies:
greatest_possibilities.append(candy + extra_candies >= greatest_candy)
return greatest_possibilities
def get_greatest(candies):
greatest = candies[0]
for candy in candies:
if candy > greatest:
greatest = candy
return greatest
data_tests = [
([2, 3, 3, 1, 3], 2, [True, True, True, True, True]),
([4, 2, 1, 1, 2], 1, [True, False, False, False, False]),
([12, 1, 12], 10, [True, False, True]),
]
for candies, extra_candies, expected in data_tests:
result = kids_with_candies(candies, extra_candies)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/guess-number-higher-or-lower/guess-number-higher-or-lower.js
================================================
// https://leetcode.com/problems/guess-number-higher-or-lower
function guessNumber(n) {
let start = 1;
let end = n;
let middle = Math.round(n / 2);
while (guess(middle)) {
if (guess(middle) > 0) {
start = middle + 1;
} else {
end = middle - 1;
}
middle = Math.round(end + start) / 2;
}
return middle;
}
================================================
FILE: coding_interviews/leetcode/easy/halves_are_alike/halves_are_alike.py
================================================
# https://leetcode.com/problems/determine-if-string-halves-are-alike/
def halves_are_alike(s):
vowels = {
'a': True,
'e': True,
'i': True,
'o': True,
'u': True,
'A': True,
'E': True,
'I': True,
'O': True,
'U': True,
}
middle_index = len(s) // 2
a, b = s[:middle_index], s[middle_index:]
a_counter, b_counter = 0, 0
for char in a:
if char in vowels:
a_counter += 1
for char in b:
if char in vowels:
b_counter += 1
return a_counter == b_counter
================================================
FILE: coding_interviews/leetcode/easy/hamming_distance/hamming_distance.py
================================================
def get_bit(number):
return "{0:b}".format(number)
def hamming_distance(x, y):
x_bit = get_bit(x)
y_bit = get_bit(y)
min_len = min(len(x_bit), len(y_bit))
max_len = max(len(x_bit), len(y_bit))
diff_len = max_len - min_len
if len(x_bit) > len(y_bit):
max_bit = x_bit
min_bit = y_bit
else:
max_bit = y_bit
min_bit = x_bit
min_bit = '0' * diff_len + min_bit
counter = 0
for index in range(max_len):
if max_bit[index] != min_bit[index]: counter += 1
return counter
def hamming_distance_2(x, y):
counter = 0
while x or y:
if (x % 2) != (y % 2): counter += 1
x //= 2
y //= 2
return counter
================================================
FILE: coding_interviews/leetcode/easy/height_checker/height_checker.py
================================================
# https://leetcode.com/problems/height-checker
def height_checker(heights):
sorted_heights, counter = sorted(heights), 0
for index in range(len(heights)):
if heights[index] != sorted_heights[index]:
counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/implement-queue-using-stacks/implement-queue-using-stacks.js
================================================
const MyQueue = function () {
this.list = [];
};
MyQueue.prototype.push = function (x) {
this.list.push(x);
};
MyQueue.prototype.pop = function () {
return this.list.shift();
};
MyQueue.prototype.peek = function () {
return this.list[0];
};
MyQueue.prototype.empty = function () {
return this.list.length === 0;
};
================================================
FILE: coding_interviews/leetcode/easy/implement-stack-using-queues/implement-stack-using-queues.js
================================================
function MyStack() {
this.items = [];
}
MyStack.prototype.push = function (x) {
this.items.push(x);
};
MyStack.prototype.pop = function () {
return this.items.pop();
};
MyStack.prototype.top = function () {
return this.items.at(-1);
};
MyStack.prototype.empty = function () {
return this.items.length === 0;
};
================================================
FILE: coding_interviews/leetcode/easy/increasing_decreasing_string/incresing_decreasin_string.py
================================================
# https://leetcode.com/problems/increasing-decreasing-string/
def sort_string(s):
result = []
while len(s):
last_appended, to_be_appended, chosen_index = float('-Inf'), float('Inf'), float('Inf')
while chosen_index is not None:
chosen_index = None
for index, char in enumerate(s):
unicode_char = ord(char)
if unicode_char > last_appended and unicode_char < to_be_appended:
to_be_appended = unicode_char
chosen_index = index
if chosen_index is not None:
result.append(chr(to_be_appended))
last_appended = to_be_appended
to_be_appended = float('Inf')
s = s[0:chosen_index] + s[chosen_index+1:]
last_appended, to_be_appended, chosen_index = float('Inf'), float('-Inf'), float('Inf')
while chosen_index is not None:
chosen_index = None
for index, char in enumerate(s):
unicode_char = ord(char)
if unicode_char < last_appended and unicode_char > to_be_appended:
to_be_appended = unicode_char
chosen_index = index
if chosen_index is not None:
result.append(chr(to_be_appended))
last_appended = to_be_appended
to_be_appended = float('-Inf')
s = s[0:chosen_index] + s[chosen_index+1:]
return ''.join(result)
================================================
FILE: coding_interviews/leetcode/easy/increasing_order_search_tree/increasing_order_search_tree.py
================================================
def increasingBST(root):
arr = []
helper(root, arr)
ans = current = TreeNode(arr[0])
for val in arr[1:]:
current.right = TreeNode(val)
current = current.right
return ans
def helper(self, old_tree, arr):
if old_tree.left: helper(old_tree.left, arr)
arr.append(old_tree.val)
if old_tree.right: helper(old_tree.right, arr)
================================================
FILE: coding_interviews/leetcode/easy/intersection-of-multiple-arrays/intersection-of-multiple-arrays.js
================================================
function intersection(nums) {
const numberCounts = new Map();
const numsLength = nums.length;
const intersectionNums = [];
for (let numsList of nums) {
for (let num of numsList) {
if (numberCounts.has(num)) {
numberCounts.set(num, numberCounts.get(num) + 1);
} else {
numberCounts.set(num, 1);
}
}
}
for (let [num, count] of numberCounts.entries()) {
if (count === numsLength) {
intersectionNums.push(num);
}
}
return intersectionNums.sort((a, b) => a - b);
}
================================================
FILE: coding_interviews/leetcode/easy/intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.js
================================================
/*
nums1 = [1,2,2,1], nums2 = [2,2] => [2] => []
result = [2,2]
Runtime: O(N^3)
Space: O(N)
nums1 = [1,2,2,1], nums2 = [2,2]
hashmap = { 1: 2, 2: 2 }; => { 1: 2, 2: 1 }; => { 1: 2, 2: 0 };
result = [2, 2]
Runtime: O(N) + O(N) => O(N)
Space: O(N) + O(N) => O(N)
*/
function intersect(nums1, nums2) {
let numsCount = {};
for (let num of nums1) {
if (numsCount[num]) {
numsCount[num]++;
} else {
numsCount[num] = 1;
}
}
let result = [];
for (let num of nums2) {
if (numsCount[num]) {
numsCount[num]--;
result.push(num);
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/intersection_of_two_arrays/intersection_of_two_arrays.py
================================================
# https://leetcode.com/problems/intersection-of-two-arrays/
def intersection(nums1, nums2):
intersect_set = set()
for num1 in nums1:
for num2 in nums2:
if num1 == num2:
intersect_set.add(num1)
return intersect_set
def intersection(nums1, nums2):
return set(nums1).intersection(nums2)
def intersection(nums1, nums2):
nums_mapper = {}
for num in nums1:
nums_mapper[num] = True
nums = set()
for num in nums2:
if num in nums_mapper:
nums.add(num)
return nums
================================================
FILE: coding_interviews/leetcode/easy/intersection_of_two_arrays_ii/intersection_of_two_arrays.py
================================================
# https://leetcode.com/problems/intersection-of-two-arrays-ii
def intersection(nums1, nums2):
hash_map = {}
for num in nums1:
if num in hash_map:
hash_map[num] += 1
else:
hash_map[num] = 1
nums = []
for num in nums2:
if num in hash_map and hash_map[num]:
nums.append(num)
hash_map[num] -= 1
return nums
================================================
FILE: coding_interviews/leetcode/easy/invert-binary-tree/invert-binary-tree.js
================================================
function invertTree(root) {
if (!root) {
return root;
}
let leftNode = root.left;
let rightNode = root.right;
root.left = invertTree(rightNode);
root.right = invertTree(leftNode);
return root;
}
================================================
FILE: coding_interviews/leetcode/easy/is-subsequence/is-subsequence.js
================================================
// https://leetcode.com/problems/is-subsequence
function isSubsequence(s, t) {
let sIndex = 0;
let tIndex = 0;
while (sIndex < s.length && tIndex < t.length) {
let sChar = s[sIndex];
let tChar = t[tIndex];
if (sChar === tChar) {
sIndex++;
tIndex++;
} else {
tIndex++;
}
}
return sIndex === s.length;
}
================================================
FILE: coding_interviews/leetcode/easy/is_palindrome.py
================================================
# https://leetcode.com/problems/palindrome-number/description/
def is_palindrome(x):
if x < 0:
return False
s = ''
while x > 0:
s += str(x % 10)
x /= 10
return s == s[::-1]
================================================
FILE: coding_interviews/leetcode/easy/is_sum_equal/is_sum_equal.py
================================================
# https://leetcode.com/problems/check-if-word-equals-summation-of-two-words
alphabet = {
'a': '0',
'b': '1',
'c': '2',
'd': '3',
'e': '4',
'f': '5',
'g': '6',
'h': '7',
'i': '8',
'j': '9',
}
def get_numerical_value(word):
list_of_chars = []
for char in word:
list_of_chars.append(alphabet[char])
return int(''.join(list_of_chars))
def is_sum_equal(first_word, second_word, target_word):
first_num = get_numerical_value(first_word)
second_num = get_numerical_value(second_word)
target_num = get_numerical_value(target_word)
return first_num + second_num == target_num
================================================
FILE: coding_interviews/leetcode/easy/island-perimeter/island-perimeter.js
================================================
function isOffGrid(grid, row, col) {
return row < 0 || row >= grid.length || col < 0 || col >= grid[0].length;
}
function isWater(grid, row, col) {
return grid[row][col] === 0;
}
function isPartOfIsland(grid, row, col) {
return grid[row][col] === 1;
}
function wasAlreadyVisited(grid, row, col) {
return grid[row][col] === 2;
}
function dfs(grid, row, col) {
if (isOffGrid(grid, row, col) || isWater(grid, row, col)) {
return 1;
}
if (wasAlreadyVisited(grid, row, col)) {
return 0;
}
grid[row][col] = 2;
return (
dfs(grid, row, col - 1) +
dfs(grid, row, col + 1) +
dfs(grid, row - 1, col) +
dfs(grid, row + 1, col)
);
}
function islandPerimeter(grid) {
let perimeter = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
if (isPartOfIsland(grid, row, col)) {
perimeter += dfs(grid, row, col);
}
}
}
return perimeter;
}
================================================
FILE: coding_interviews/leetcode/easy/jewels_and_stones.py
================================================
# https://leetcode.com/problems/jewels-and-stones/description/
# input: J = "aA" | S = "aAAbbbb"
# output: 3
# input: J = "z", S = "ZZ"
# output: 0
# Solution: O(N^2)
def num_jewels_in_stones(J, S):
jewels = 0
for j in J:
for s in S:
if s == j:
jewels += 1
return jewels
print(num_jewels_in_stones("aA", "aAAbbbb"))
print(num_jewels_in_stones("z", "ZZ"))
# Solution: O(N)
def num_jewels_in_stones_opt(J, S):
number_by_chars = {}
counter = 0
for char in J:
if char in number_by_chars:
number_by_chars[char] += 1
else:
number_by_chars[char] = 1
for char in S:
if char in number_by_chars:
counter += number_by_chars[char]
return counter
print(num_jewels_in_stones_opt("aA", "aAAbbbb"))
print(num_jewels_in_stones_opt("z", "ZZ"))
================================================
FILE: coding_interviews/leetcode/easy/judge_route_circle.py
================================================
'''
https://leetcode.com/problems/judge-route-circle/description/
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
'''
def judge_circle(moves):
horizontal, vertical = 0, 0
moves_mapper = { 'U': 1, 'D': -1, 'R': 1, 'L': -1 }
for move in moves:
if move in ['U', 'D']:
vertical += moves_mapper[move]
else:
horizontal += moves_mapper[move]
return horizontal == 0 and vertical == 0
print(judge_circle("UD"))
print(judge_circle("LL"))
================================================
FILE: coding_interviews/leetcode/easy/judge_route_circle_one_line.py
================================================
'''
https://leetcode.com/problems/judge-route-circle/description/
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
'''
def judge_circle(moves):
return moves.count("U") == moves.count("D") and moves.count("R") == moves.count("L")
print(judge_circle("UD"))
print(judge_circle("LL"))
================================================
FILE: coding_interviews/leetcode/easy/k-items-with-the-maximum-sum/k-items-with-the-maximum-sum-second.js
================================================
// https://leetcode.com/problems/k-items-with-the-maximum-sum
function kItemsWithMaximumSum(numOnes, numZeros, numNegOnes, k) {
if (k <= numOnes) {
return k;
}
let sum = 0;
if (numOnes) {
sum += numOnes;
k -= numOnes;
}
if (k > 0 && numZeros) {
k -= numZeros;
}
if (k > 0 && numNegOnes) {
sum -= k;
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/k-items-with-the-maximum-sum/k-items-with-the-maximum-sum.js
================================================
// https://leetcode.com/problems/k-items-with-the-maximum-sum
function kItemsWithMaximumSum(numOnes, numZeros, numNegOnes, k) {
let max = 0;
let mutK = k;
mutK -= numOnes;
if (mutK <= 0) return k;
max += numOnes;
mutK -= numZeros;
if (mutK <= 0) return max;
if (mutK - numNegOnes < 0) return max - mutK;
max -= numNegOnes;
return max;
}
================================================
FILE: coding_interviews/leetcode/easy/keep-multiplying-found-values-by-two/keep-multiplying-found-values-by-two.js
================================================
function findFinalValue(nums, original) {
let keepProcessing = true;
let originalCopy = original;
while (keepProcessing) {
let foundOriginal = false;
for (let num of nums) {
if (num === originalCopy) {
foundOriginal = true;
}
}
if (foundOriginal) {
originalCopy *= 2;
} else {
keepProcessing = false;
}
}
return originalCopy;
}
================================================
FILE: coding_interviews/leetcode/easy/keyboard-row/keyboard-row.js
================================================
function stringToMap(string) {
const map = new Map();
for (let char of string) {
map.set(char, true);
}
return map;
}
const firstRow = stringToMap('qwertyuiop');
const secondRow = stringToMap('asdfghjkl');
const thirdRow = stringToMap('zxcvbnm');
function belongsToRow(word, row) {
for (let char of word) {
if (!row.has(char)) {
return false;
}
}
return true;
}
function belongsToSomeRow(word) {
let belongsToARow = belongsToRow(word, firstRow);
if (belongsToARow) return true;
belongsToARow = belongsToRow(word, secondRow);
if (belongsToARow) return true;
belongsToARow = belongsToRow(word, thirdRow);
return belongsToARow;
}
function findWords(words) {
const result = [];
for (let word of words) {
if (belongsToSomeRow(word.toLowerCase())) {
result.push(word);
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/kth-distinct-string-in-an-array/kth-distinct-string-in-an-array.js
================================================
function kthDistinct(arr, k) {
let count = 0;
let hashmap = new Map();
for (let string of arr) {
if (hashmap.has(string)) {
hashmap.set(string, hashmap.get(string) + 1);
} else {
hashmap.set(string, 1);
}
}
let distinctStrings = [];
hashmap.forEach((count, string) => {
if (count === 1) {
distinctStrings.push(string);
}
});
for (let string of distinctStrings) {
count++;
if (count === k) return string;
}
return '';
}
function kthDistinct(arr, k) {
let hashmap = new Map();
for (let string of arr) {
if (hashmap.has(string)) {
hashmap.set(string, hashmap.get(string) + 1);
} else {
hashmap.set(string, 1);
}
}
let distinctStrings = [];
hashmap.forEach((count, string) => {
if (count === 1) {
distinctStrings.push(string);
}
});
return distinctStrings[k - 1] || '';
}
================================================
FILE: coding_interviews/leetcode/easy/largest-local-values-in-a-matrix/largest-local-values-in-a-matrix.js
================================================
function getLargestFromGrid(grid, startRow, startCol, endRow, endCol) {
let largest = -Infinity;
for (let row = startRow; row <= endRow; row++) {
for (let col = startCol; col <= endCol; col++) {
largest = Math.max(largest, grid[row][col]);
}
}
return largest;
}
function largestLocal(grid) {
const generatedGrid = [];
for (let row = 0; row < grid.length - 2; row++) {
const generatedRow = [];
for (let col = 0; col < grid[row].length - 2; col++) {
generatedRow.push(getLargestFromGrid(grid, row, col, row + 2, col + 2));
}
generatedGrid.push(generatedRow);
}
return generatedGrid;
}
================================================
FILE: coding_interviews/leetcode/easy/largest-number-after-digit-swaps-by-parity/largest-number-after-digit-swaps-by-parity.js
================================================
// https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity
const isEven = (num) => num % 2 === 0;
const isOdd = (num) => !isEven(num);
function largestInteger(num) {
let numString = num.toString().split('');
for (let index = 0; index < numString.length - 1; index++) {
let digit = Number(numString[index]);
let isDigitEven = isEven(digit);
let maxDigit = digit;
let swapIndex1 = index;
let swapIndex2;
for (
let digitIndex = index + 1;
digitIndex < numString.length;
digitIndex++
) {
let otherDigit = Number(numString[digitIndex]);
let isOtherDigitEven = isEven(otherDigit);
if (isDigitEven && isOtherDigitEven && otherDigit > maxDigit) {
maxDigit = otherDigit;
swapIndex2 = digitIndex;
}
if (!isDigitEven && !isOtherDigitEven && otherDigit > maxDigit) {
maxDigit = otherDigit;
swapIndex2 = digitIndex;
}
}
if (swapIndex2) {
let aux = numString[swapIndex1];
numString[swapIndex1] = numString[swapIndex2];
numString[swapIndex2] = aux;
}
}
return numString.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/largest-positive-integer-that-exists-with-its-negative/largest-positive-integer-that-exists-with-its-negative.js
================================================
function findMaxK(nums) {
const hashmap = new Map();
for (let num of nums) {
if (!hashmap.has(num)) hashmap.set(num, true);
}
let output = -1;
for (let num of nums) {
if (num > output && hashmap.has(num * -1)) {
output = num;
}
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/last-stone-weight/last-stone-weight.js
================================================
function getTwoHaviest(stones) {
const first = stones[0];
const second = stones[1];
let heaviest = first > second ? first : second;
let secondHeaviest = first > second ? second : first;
for (let i = 2; i < stones.length; i++) {
const stone = stones[i];
if (stone > heaviest) {
secondHeaviest = heaviest;
heaviest = stone;
continue;
}
if (stone > secondHeaviest) {
secondHeaviest = stone;
continue;
}
}
return { heaviest, secondHeaviest };
}
function removeStone(stones, stoneToBeRemoved) {
for (let i = 0; i < stones.length; i++) {
if (stones[i] === stoneToBeRemoved) {
stones.splice(i, 1);
return;
}
}
}
function updateStone(stones, stone, stoneWeight) {
for (let i = 0; i < stones.length; i++) {
if (stones[i] === stone) {
stones[i] = stoneWeight;
return;
}
}
}
export function lastStoneWeight(stones) {
while (stones.length > 1) {
const { heaviest, secondHeaviest } = getTwoHaviest(stones);
if (heaviest === secondHeaviest) {
removeStone(stones, heaviest);
removeStone(stones, secondHeaviest);
}
if (heaviest !== secondHeaviest) {
updateStone(stones, heaviest, heaviest - secondHeaviest);
removeStone(stones, secondHeaviest);
}
}
return stones[0] || 0;
}
================================================
FILE: coding_interviews/leetcode/easy/last-stone-weight/tests/last-stone-weight.test.js
================================================
import { describe, expect, it } from 'vitest';
import { lastStoneWeight } from '../last-stone-weight';
describe('lastStoneWeight', () => {
it('', () => {
expect(lastStoneWeight([2, 7, 4, 1, 8, 1])).toEqual(1);
});
it('', () => {
expect(lastStoneWeight([1])).toEqual(1);
});
it('', () => {
expect(lastStoneWeight([2, 2])).toEqual(0);
});
it('', () => {
expect(lastStoneWeight([10, 4, 2, 10])).toEqual(2);
});
});
================================================
FILE: coding_interviews/leetcode/easy/last-visited-integers/last-visited-integers.js
================================================
// https://leetcode.com/problems/last-visited-integers
function getLastInteger(words, lastNumberIndex, consecutivePrevs) {
for (let index = lastNumberIndex; index >= 0; index--) {
while (words[index] === 'prev') {
index--;
}
if (index < 0) {
return -1;
}
if (consecutivePrevs === 0) {
return words[index];
}
if (words[index] !== 'prev') {
consecutivePrevs--;
}
}
return -1;
}
function lastVisitedIntegers(words) {
let result = [];
let consecutivePrevs = 0;
let lastNumberIndex;
for (let index = 0; index < words.length; index++) {
if (words[index] === 'prev') {
result.push(getLastInteger(words, lastNumberIndex, consecutivePrevs));
consecutivePrevs++;
} else {
lastNumberIndex = index;
consecutivePrevs = 0;
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/leaf-similar-trees/leaf-similar-trees.js
================================================
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
function getLeafValueSequence(node, leafValueSequence) {
if (!node) return;
if (!node.left && !node.right) {
leafValueSequence.push(node.val);
return;
}
getLeafValueSequence(node.left, leafValueSequence);
getLeafValueSequence(node.right, leafValueSequence);
}
function hasSimilarLeafSequence(leafValueSequence1, leafValueSequence2) {
if (leafValueSequence1.length !== leafValueSequence2.length) return false;
for (let index = 0; index < leafValueSequence1.length; index++) {
if (leafValueSequence1[index] !== leafValueSequence2[index]) return false;
}
return true;
}
function leafSimilar(root1, root2) {
let leafValueSequence1 = [];
let leafValueSequence2 = [];
getLeafValueSequence(root1, leafValueSequence1);
getLeafValueSequence(root2, leafValueSequence2);
return hasSimilarLeafSequence(leafValueSequence1, leafValueSequence2);
}
================================================
FILE: coding_interviews/leetcode/easy/left-and-right-sum-differences/left-and-right-sum-differences.js
================================================
function sum(nums) {
let sumOfNums = 0;
for (let num of nums) {
sumOfNums += num;
}
return sumOfNums;
}
function leftRigthDifference(nums) {
let rightSum = sum(nums);
let leftSum = 0;
let previous = 0;
let answer = [];
for (let num of nums) {
leftSum += previous;
rightSum -= num;
previous = num;
answer.push(Math.abs(leftSum - rightSum));
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/easy/length-of-last-word/length-of-last-word.js
================================================
// https://leetcode.com/problems/length-of-last-word
const lengthOfLastWord = (s) => {
const words = s.trim().split(' ');
return words[words.length - 1].length;
};
const lengthOfLastWord = (s) => {
let lastWordLength = 0;
for (let i = s.length - 1; i >= 0; i--) {
if (s[i] !== ' ') lastWordLength++;
if (s[i] === ' ' && lastWordLength > 0) break;
}
return lastWordLength;
};
================================================
FILE: coding_interviews/leetcode/easy/lexicographically-smallest-palindrome/lexicographically-smallest-palindrome.js
================================================
function makeSmallestPalindrome(string) {
let start = 0;
let end = string.length - 1;
let palindrome = [];
while (start <= end) {
let charCode1 = string.charCodeAt(start);
let charCode2 = string.charCodeAt(end);
if (charCode1 <= charCode2) {
palindrome[start] = string[start];
palindrome[end] = string[start];
}
if (charCode2 < charCode1) {
palindrome[start] = string[end];
palindrome[end] = string[end];
}
start++;
end--;
}
return palindrome.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/linked-list-cycle/linked-list-cycle.js
================================================
function hasCycle(head) {
let fast = head;
while (fast && fast.next) {
head = head.next;
fast = fast.next.next;
if (head === fast) {
return true;
}
}
return false;
}
================================================
FILE: coding_interviews/leetcode/easy/longer-contiguous-segments-of-ones-than-zeros/longer-contiguous-segments-of-ones-than-zeros.js
================================================
function checkZeroOnes(s) {
let zerosLongestContinuousSegment = 0;
let onesLongestContinuousSegment = 0;
let zerosContinuousSegment = 0;
let onesContinuousSegment = 0;
for (let index = 0; index < s.length; index++) {
let char = s[index];
if (char === '1') {
zerosLongestContinuousSegment = Math.max(
zerosLongestContinuousSegment,
zerosContinuousSegment
);
zerosContinuousSegment = 0;
onesContinuousSegment++;
} else {
onesLongestContinuousSegment = Math.max(
onesLongestContinuousSegment,
onesContinuousSegment
);
onesContinuousSegment = 0;
zerosContinuousSegment++;
}
if (index === s.length - 1) {
if (char === '1') {
onesLongestContinuousSegment = Math.max(
onesLongestContinuousSegment,
onesContinuousSegment
);
} else {
zerosLongestContinuousSegment = Math.max(
zerosLongestContinuousSegment,
zerosContinuousSegment
);
}
}
}
return onesLongestContinuousSegment > zerosLongestContinuousSegment;
}
================================================
FILE: coding_interviews/leetcode/easy/longest-nice-substring/longest-nice-substring.js
================================================
function isNice(substring, map) {
for (let char of substring) {
if (!map.has(char.toLowerCase()) || !map.has(char.toUpperCase())) {
return false;
}
}
return true;
}
function longestNiceSubstring(s) {
let substring = '';
for (let i = 0; i < s.length; i++) {
let newSubstring = [s[i]];
let map = new Map([[s[i], true]]);
for (let j = i + 1; j < s.length; j++) {
newSubstring.push(s[j]);
map.set(s[j], true);
if (isNice(newSubstring, map) && newSubstring.length > substring.length) {
substring = newSubstring.join('');
}
}
}
return substring;
}
================================================
FILE: coding_interviews/leetcode/easy/longest-subsequence-with-limited-sum/longest-subsequence-with-limited-sum.js
================================================
function immutableSort(nums) {
return [...nums].sort((a, b) => a - b);
}
function buildAllSums(nums) {
let allSums = [];
let sum = 0;
for (num of nums) {
sum += num;
allSums.push(sum);
}
return allSums;
}
function answerQueries(nums, queries) {
let answer = [];
let sortedNums = immutableSort(nums);
let allSums = buildAllSums(sortedNums);
for (let query of queries) {
let num;
for (let index = 0; index < allSums.length; index++) {
let sum = allSums[index];
if (sum <= query) {
num = index + 1;
if (index === allSums.length - 1) answer.push(num);
} else {
if (num) answer.push(num);
break;
}
}
if (!num) answer.push(0);
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/easy/longest_palindrome.py
================================================
def count_pairs(letters):
hash = {}
result = {"pair": 0, "single": 0}
for letter in letters:
if hash.get(letter):
hash[letter] += 1
else:
hash[letter] = 1
for k, v in hash.items():
if v > 1:
result["pair"] += v - (v % 2)
result["single"] += v % 2
else:
result["single"] += 1
return result
def main(letters):
counter = 0
pairs = count_pairs(letters)
counter += pairs["pair"]
if pairs["single"] > 0:
counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.js
================================================
function lowestCommonAncestor(root, p, q) {
if (root === p || root === q) {
return root;
}
if (
(p.val < root.val && q.val > root.val) ||
(p.val > root.val && q.val < root.val)
) {
return root;
}
if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
}
if (p.val > root.val && q.val > root.val) {
return lowestCommonAncestor(root.right, p, q);
}
}
================================================
FILE: coding_interviews/leetcode/easy/lucky_numbers_in_a_matrix/lucky_numbers_in_a_matrix.py
================================================
# https://leetcode.com/problems/lucky-numbers-in-a-matrix
def lucky_numbers(matrix):
all_lucky_numbers, all_mins = [], []
for row in matrix:
found_min, col_index = float('Inf'), -1
for index, column in enumerate(row):
if column < found_min:
found_min = column
col_index = index
all_mins.append([found_min, col_index])
for a_min in all_mins:
[min_value, min_column] = a_min
maximum = float('-Inf')
for index in range(len(matrix)):
num = matrix[index][min_column]
maximum = max(num, maximum)
if maximum == min_value:
all_lucky_numbers.append(min_value)
return all_lucky_numbers
================================================
FILE: coding_interviews/leetcode/easy/majority-element/majority-element.js
================================================
function majorityElement(nums) {
let hashmap = {};
let result;
for (let num of nums) {
if (hashmap[num]) {
hashmap[num]++;
} else {
hashmap[num] = 1;
}
}
Object.entries(hashmap).forEach(([num, count]) => {
if (count > nums.length / 2) {
result = num;
}
});
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/make-array-zero-by-subtracting-equal-amounts/make-array-zero-by-subtracting-equal-amounts.js
================================================
function minimumOperationsAllInOne(nums) {
let count = 0;
let smallest = 0;
for (let num of nums) {
if (num > 0) {
smallest = smallest ? Math.min(smallest, num) : num;
}
}
while (smallest) {
let smallestToSubtract = smallest;
smallest = 0;
for (let index = 0; index < nums.length; index++) {
let subtractionResult = nums[index] - smallestToSubtract;
nums[index] = subtractionResult > 0 ? subtractionResult : 0;
if (subtractionResult > 0) {
smallest = smallest
? Math.min(smallest, subtractionResult)
: subtractionResult;
}
}
count++;
}
return count;
}
// --------------------------------------------------
function smallestExceptZeros(smallest, num) {
return smallest ? Math.min(smallest, num) : num;
}
function getSmallest(nums) {
let smallest = 0;
for (let num of nums) {
if (num > 0) {
smallest = smallestExceptZeros(smallest, num);
}
}
return smallest;
}
function performSubtraction(nums, smallestToSubtract, smallest) {
for (let index = 0; index < nums.length; index++) {
let subtractionResult = nums[index] - smallestToSubtract;
nums[index] = subtractionResult > 0 ? subtractionResult : 0;
if (subtractionResult > 0) {
smallest = smallestExceptZeros(smallest, subtractionResult);
}
}
return smallest;
}
function minimumOperations(nums) {
let count = 0;
let smallest = getSmallest(nums);
while (smallest) {
smallest = performSubtraction(nums, smallest, 0);
count++;
}
return count;
}
// --------------------------------------------------
function minimumOperationsSet(nums) {
return new Set(nums.filter((num) => num !== 0));
}
================================================
FILE: coding_interviews/leetcode/easy/make-the-string-great/make-the-string-great.js
================================================
function isUpperCase(char1, char2) {
return char1 !== char1.toUpperCase() && char1.toUpperCase() === char2;
}
function isLowerCase(char1, char2) {
return char2.toLowerCase() !== char2 && char2.toLowerCase() === char1;
}
function isBadPair(char1, char2) {
return (
isUpperCase(char1, char2) ||
isUpperCase(char2, char1) ||
isLowerCase(char1, char2) ||
isLowerCase(char2, char1)
);
}
function makeGood(string, pointer1 = 0, pointer2 = 1) {
if (string.length <= 1) return string;
if (pointer2 === string.length) return string;
console.log(
string[pointer1],
string[pointer2],
isBadPair(string[pointer1], string[pointer2])
);
if (isBadPair(string[pointer1], string[pointer2])) {
return makeGood(
string.slice(0, pointer1) + string.slice(pointer2 + 1),
0,
1
);
}
return makeGood(string, pointer1 + 1, pointer2 + 1);
}
================================================
FILE: coding_interviews/leetcode/easy/matrix-cells-in-distance-order/matrix-cells-in-distance-order.js
================================================
function sortDistances(distances) {
return [...distances].sort((distance1, distance2) => distance1 - distance2);
}
function allCellsDistOrder(rows, cols, rCenter, cCenter) {
const distancesMap = new Map();
const distances = [];
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const distance = Math.abs(row - rCenter) + Math.abs(col - cCenter);
if (distancesMap.has(distance)) {
distancesMap.set(distance, [...distancesMap.get(distance), [row, col]]);
} else {
distances.push(distance);
distancesMap.set(distance, [[row, col]]);
}
}
}
return sortDistances(distances)
.map((distance) => distancesMap.get(distance))
.flatMap((cell) => cell);
}
================================================
FILE: coding_interviews/leetcode/easy/matrix_diagonal_sum/matrix_diagonal_sum.py
================================================
# https://leetcode.com/problems/matrix-diagonal-sum
'''
Time Complexity: O(N)
Space Complexity: O(1)
'''
def diagonal_sum(mat):
diagonals_sum, mat_length = 0, len(mat)
# left-top --> right-bottom & right-top --> left-bottom
for index in range(mat_length):
diagonals_sum += mat[index][index] + mat[index][mat_length-index-1]
if len(mat) % 2 == 0:
return diagonals_sum
center = mat_length // 2
return diagonals_sum - mat[center][center]]
================================================
FILE: coding_interviews/leetcode/easy/matrix_negative_numbers/matrix_negative_numbers.py
================================================
def count_negatives(grid):
counter = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] < 0:
counter += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/max-consecutive-ones/max-consecutive-ones.js
================================================
function findMaxConsecutiveOnes(nums) {
let max = 0;
let consecutive = 0;
for (let index = 0; index < nums.length; index++) {
if (nums[index] === 1) consecutive++;
if (nums[index] === 0 || index === nums.length - 1) {
max = Math.max(max, consecutive);
consecutive = 0;
}
}
return max;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-69-number/maximum-69-number.js
================================================
function maximum69Number(num) {
let nums = String(num).split('');
let firstSixIndex;
for (let index = 0; index < nums.length; index++) {
if (nums[index] === '6' && firstSixIndex === undefined) {
firstSixIndex = index;
}
}
nums[firstSixIndex] = '9';
return Number(nums.join(''));
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-ascending-subarray-sum/maximum-ascending-subarray-sum.js
================================================
function maxAscendingSum(nums) {
let max = 0;
let maxSubsequence = 0;
let previous = -Infinity;
for (let index = 0; index < nums.length; index++) {
let num = nums[index];
if (num > previous) {
maxSubsequence += num;
previous = num;
if (index === nums.length - 1) max = Math.max(max, maxSubsequence);
} else {
max = Math.max(max, maxSubsequence);
previous = num;
maxSubsequence = num;
}
}
return max;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-count-of-positive-integer-and-negative-integer/maximum-count-of-positive-integer-and-negative-integer.js
================================================
function maximumCount(nums) {
let pos = 0;
let neg = 0;
for (let num of nums) {
if (num > 0) pos++;
if (num < 0) neg++;
}
return Math.max(pos, neg);
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree-2.js
================================================
function getMaximumDepth(node, depth) {
if (!node) {
return depth;
}
return Math.max(
getMaximumDepth(node.left, depth + 1),
getMaximumDepth(node.right, depth + 1)
);
}
function maxDepth(root) {
if (!root) {
return 0;
}
return Math.max(
getMaximumDepth(root.left, 1),
getMaximumDepth(root.right, 1)
);
}
// shorter without a helper function
function maxDepth(root, depth = 0) {
return root
? Math.max(maxDepth(root.left, depth + 1), maxDepth(root.right, depth + 1))
: depth;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js
================================================
// https://leetcode.com/problems/maximum-depth-of-binary-tree
const maxDepth = (root) => maxDepthHelper(root, 0);
const maxDepthHelper = (node, depth) => {
if (!node) return depth;
const leftDepth = maxDepthHelper(node.left, depth + 1);
const rightDepth = maxDepthHelper(node.right, depth + 1);
return Math.max(leftDepth, rightDepth);
};
================================================
FILE: coding_interviews/leetcode/easy/maximum-depth-of-n-ary-tree/maximum-depth-of-n-ary-tree.js
================================================
function maxDepth(root, depth = 1) {
if (!root) return depth - 1;
let depths = [];
for (let child of root.children) {
const childDepth = maxDepth(child, depth + 1);
depths.push(childDepth);
}
return depths.length ? Math.max(...depths) : depth;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-number-of-balloons/maximum-number-of-balloons.js
================================================
function buildHashmap(text) {
const hashmap = new Map();
for (let char of text) {
if (hashmap.has(char)) hashmap.set(char, hashmap.get(char) + 1);
else hashmap.set(char, 1);
}
return hashmap;
}
function maxNumberOfBalloons(text) {
let hashmap = buildHashmap(text);
let minCharCount = Infinity;
let balloon = 'balon';
for (let char of balloon) {
if (!hashmap.has(char)) return 0;
if (['l', 'o'].includes(char))
minCharCount = Math.min(minCharCount, Math.floor(hashmap.get(char) / 2));
else minCharCount = Math.min(minCharCount, hashmap.get(char));
}
return minCharCount;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-number-of-pairs-in-array/maximum-number-of-pairs-in-array.js
================================================
function numberOfPairs(nums) {
let countNums = new Map();
for (let num of nums) {
if (countNums.has(num)) {
countNums.set(num, countNums.get(num) + 1);
} else {
countNums.set(num, 1);
}
}
let pairs = 0;
let rest = 0;
countNums.forEach((num) => {
pairs += Math.floor(num / 2);
rest += Math.floor(num % 2);
});
return [pairs, rest];
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-odd-binary-number/maximum-odd-binary-number.js
================================================
// https://leetcode.com/problems/maximum-odd-binary-number
function countOnesAndZeros(s) {
let countOnes = 0;
let countZeros = 0;
for (let char of s) {
if (char === '1') {
countOnes++;
} else {
countZeros++;
}
}
return { countOnes, countZeros };
}
function maximumOddBinaryNumber(s) {
const { countOnes, countZeros } = countOnesAndZeros(s);
let result = '';
for (let one = 1; one <= countOnes - 1; one++) {
result += '1';
}
for (let zero = 1; zero <= countZeros; zero++) {
result += '0';
}
return result + '1';
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-subarray/maximum-subarray.js
================================================
function maxSubArray(nums) {
let maxSum = nums[0];
let localSum = nums[0];
for (let index = 1; index < nums.length; index++) {
localSum = Math.max(nums[index], localSum + nums[index]);
maxSum = Math.max(maxSum, localSum);
}
return maxSum;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-sum-with-exactly-k-elements/maximum-sum-with-exactly-k-elements.js
================================================
function getBiggest(nums) {
let biggest = -Infinity;
for (let num of nums) {
biggest = Math.max(biggest, num);
}
return biggest;
}
function maximizeSum(nums, k) {
let biggest = getBiggest(nums);
let sum = 0;
while (k--) {
sum += biggest;
biggest++;
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/maximum-units-on-a-truck/maximum-units-on-a-truck.py
================================================
# https://leetcode.com/problems/maximum-units-on-a-truck
def maximum_units(box_types, truck_size):
sorted_by_units_per_box = sorted(box_types, key=lambda box_type: box_type[1], reverse=True)
units = 0
for [num_of_boxes, num_of_units] in sorted_by_units_per_box:
num_of_boxes_to_put_on_the_truck = min(truck_size, num_of_boxes)
truck_size -= num_of_boxes_to_put_on_the_truck
units += num_of_boxes_to_put_on_the_truck * num_of_units
if truck_size <= 0: break
return units
================================================
FILE: coding_interviews/leetcode/easy/maximum-value-of-a-string-in-an-array/maximum-value-of-a-string-in-an-array.js
================================================
function maximumValue(strs) {
return strs.reduce(
(max, string) =>
Math.max(
max,
Number.isNaN(Number(string)) ? string.length : Number(string)
),
0
);
}
================================================
FILE: coding_interviews/leetcode/easy/maximum_nesting_depth_of_the_parentheses/maximum_nesting_depth_of_the_parentheses.py
================================================
# https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses
def max_depth(s):
depth = open_paren = 0
for char in s:
if char == '(':
open_paren += 1
depth = max(depth, open_paren)
if char == ')':
open_paren -= 1
return depth
================================================
FILE: coding_interviews/leetcode/easy/maximum_number_of_balls_in_a_box/maximum_number_of_balls_in_a_box.py
================================================
# https://leetcode.com/problems/maximum-number-of-balls-in-a-box
def get_box(ball):
count = 0
while ball > 0:
count += ball % 10
ball //= 10
return count
def count_balls(low_limit, high_limit):
hash_counter = {}
for ball in range(low_limit, high_limit + 1):
box = get_box(ball)
if box in hash_counter:
hash_counter[box] += 1
else:
hash_counter[box] = 1
max_balls = float('-Inf')
for key, value in hash_counter.items():
max_balls = max(max_balls, value)
return max_balls
================================================
FILE: coding_interviews/leetcode/easy/maximum_number_of_words_you_can_type/maximum_number_of_words_you_can_type.js
================================================
// https://leetcode.com/problems/maximum-number-of-words-you-can-type
const canBeTypedWords = function (text, brokenLetters) {
const words = text.split(' ');
const broken = buildBrokenMapper(brokenLetters);
const okWords = words.filter((word) => {
let foundBroken = false;
for (let char of word) {
if (broken[char]) {
foundBroken = true;
}
}
return !foundBroken;
});
return okWords.length;
};
const buildBrokenMapper = (brokenLetters) => {
const mapper = {};
for (let letter of brokenLetters) {
mapper[letter] = true;
}
return mapper;
};
================================================
FILE: coding_interviews/leetcode/easy/maximum_population/maximum_population.py
================================================
# https://leetcode.com/problems/maximum-population-year
def maximum_population(logs):
population_by_year = {}
for [birth, death] in logs:
for year in range(birth, death):
if year in population_by_year:
population_by_year[year] += 1
else:
population_by_year[year] = 1
earliest_year = 0
max_population = 0
for year, population in population_by_year.items():
if population == max_population:
earliest_year = min(earliest_year, year)
if population > max_population:
earliest_year = year
max_population = population
return earliest_year
================================================
FILE: coding_interviews/leetcode/easy/maximum_product/maximum_product.py
================================================
# https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array
def max_product(nums):
sorted_list = sorted(nums)
return (sorted_list[-1] - 1) * (sorted_list[-2] - 1)
def max_product(nums):
max, second_max = 0, 0
for num in nums:
if num >= max:
second_max = max
max = num
elif num >= second_max:
second_max = num
return (max - 1) * (second_max - 1)
================================================
FILE: coding_interviews/leetcode/easy/maximum_product_difference_between_two_pairs/maximum_product_difference_between_two_pairs.js
================================================
// https://leetcode.com/problems/maximum-product-difference-between-two-pairs
const maxProductDifference = function (nums) {
nums.sort((a, b) => a - b);
const greatest = nums[nums.length - 1];
const secondGreatest = nums[nums.length - 2];
const smallest = nums[0];
const secondSmallest = nums[1];
return greatest * secondGreatest - smallest * secondSmallest;
};
const max = maxProductDifference([1, 6, 7, 5, 2, 4, 10, 6, 4]);
console.log(max);
================================================
FILE: coding_interviews/leetcode/easy/mean-of-array-after-removing-some-elements/mean-of-array-after-removing-some-elements.js
================================================
function removeFivePercent(numbers) {
let totalNumbers = numbers.length;
let fivePercent = numbers.length * 0.05;
return numbers.slice(fivePercent, totalNumbers - fivePercent);
}
function sum(numbers) {
return numbers.reduce((sumOfNums, num) => sumOfNums + num, 0);
}
function trimMean(numbers) {
numbers.sort((a, b) => a - b);
const withoutFivePercent = removeFivePercent(numbers);
const sumOfNums = sum(withoutFivePercent);
return sumOfNums / withoutFivePercent.length;
}
================================================
FILE: coding_interviews/leetcode/easy/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js
================================================
export class ListNode {
constructor(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
export function mergeNodes(head) {
let nonZeroHead;
let node;
let nextNode;
let currentNode = head.next;
let valueSum = 0;
let gotFirstNode = false;
while (currentNode) {
valueSum += currentNode.val;
if (currentNode.val === 0) {
nextNode = new ListNode(valueSum);
valueSum = 0;
if (gotFirstNode) {
node.next = nextNode;
node = node.next;
} else {
node = nextNode;
nonZeroHead = nextNode;
gotFirstNode = true;
}
}
currentNode = currentNode.next;
}
return nonZeroHead;
}
================================================
FILE: coding_interviews/leetcode/easy/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js
================================================
import { describe, it, expect } from 'vitest';
import { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros';
function buildList(nums, initValue = 0) {
let head = new ListNode(initValue);
let node = head;
let nextNode;
for (let i = 1; i < nums.length; i++) {
nextNode = new ListNode(nums[i]);
node.next = nextNode;
node = node.next;
}
return head;
}
describe('mergeNodes', () => {
it('removes zeros and merges nodes', () => {
const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]);
const result = buildList([4, 11], 4);
expect(mergeNodes(head)).toEqual(result);
});
it('removes zeros and merges nodes', () => {
const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]);
const result = buildList([1, 3, 4], 1);
expect(mergeNodes(head)).toEqual(result);
});
});
================================================
FILE: coding_interviews/leetcode/easy/merge-similar-items/merge-similar-items.js
================================================
function fillHashmapAndList(items, hashmap, list) {
for (let [value, weight] of items) {
if (hashmap.has(value)) {
hashmap.set(value, hashmap.get(value) + weight);
} else {
hashmap.set(value, weight);
list.push(value);
}
}
}
function mergeSimilarItems(items1, items2) {
let hashmap = new Map();
let list = [];
fillHashmapAndList(items1, hashmap, list);
fillHashmapAndList(items2, hashmap, list);
return list.sort((a, b) => a - b).map((value) => [value, hashmap.get(value)]);
}
================================================
FILE: coding_interviews/leetcode/easy/merge-sorted-array/merge-sorted-array.js
================================================
/*
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
[1,2,2,3,5,6]
nums1 = [0,0,0], m = 0, nums2 = [1,2,3], n = 3
[1,2,3]
time: O(n + m)
space: O(n + m)
*/
function merge(nums1, m, nums2, n) {
let pointer1 = 0;
let pointer2 = 0;
let numbers = [];
let mIndex = m - 1;
let nIndex = n - 1;
while (pointer1 <= mIndex || pointer2 <= nIndex) {
if (pointer1 <= mIndex && pointer2 <= nIndex) {
let num1 = nums1[pointer1];
let num2 = nums2[pointer2];
if (num1 <= num2) {
numbers.push(num1);
pointer1++;
} else {
numbers.push(num2);
pointer2++;
}
}
if (pointer1 <= mIndex && pointer2 > nIndex) {
numbers.push(nums1[pointer1]);
pointer1++;
}
if (pointer2 <= nIndex && pointer1 > mIndex) {
numbers.push(nums2[pointer2]);
pointer2++;
}
}
for (let [index, num] of numbers.entries()) {
nums1[index] = num;
}
}
================================================
FILE: coding_interviews/leetcode/easy/merge-two-2d-arrays-by-summing-values/merge-two-2d-arrays-by-summing-values.js
================================================
function mergeArrays(nums1, nums2) {
let nums = [];
let index1 = 0;
let index2 = 0;
while (index1 < nums1.length && index2 < nums2.length) {
let [id1, val1] = nums1[index1];
let [id2, val2] = nums2[index2];
if (id1 < id2) {
nums.push([id1, val1]);
index1++;
} else if (id2 < id1) {
nums.push([id2, val2]);
index2++;
} else {
nums.push([id1, val1 + val2]);
index1++;
index2++;
}
}
while (index1 < nums1.length) {
nums.push(nums1[index1]);
index1++;
}
while (index2 < nums2.length) {
nums.push(nums2[index2]);
index2++;
}
return nums;
}
================================================
FILE: coding_interviews/leetcode/easy/merge-two-binary-trees/merge-two-binary-trees.js
================================================
function mergeTrees(root1, root2) {
let root = new TreeNode();
if (root1 && root2) {
root.val = root1.val + root2.val;
root.left = mergeTrees(root1.left, root2.left);
root.right = mergeTrees(root1.right, root2.right);
} else if (root1) {
root = root1;
} else if (root2) {
root = root2;
} else {
return null;
}
return root;
}
================================================
FILE: coding_interviews/leetcode/easy/merge-two-sorted-lists/merge-two-sorted-lists.js
================================================
export class ListNode {
constructor(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
export function mergeTwoLists(list1, list2) {
if (!list1 && !list2) {
return null;
}
if (!list1) {
return list2;
}
if (!list2) {
return list1;
}
let newList;
if (list1.val <= list2.val) {
newList = new ListNode(list1.val);
list1 = list1.next;
} else {
newList = new ListNode(list2.val);
list2 = list2.next;
}
let node = newList;
while (list1 && list2) {
if (list1.val <= list2.val) {
node.next = new ListNode(list1.val);
list1 = list1.next;
} else {
node.next = new ListNode(list2.val);
list2 = list2.next;
}
node = node.next;
}
while (list1) {
node.next = new ListNode(list1.val);
node = node.next;
list1 = list1.next;
}
while (list2) {
node.next = new ListNode(list2.val);
node = node.next;
list2 = list2.next;
}
return newList;
}
================================================
FILE: coding_interviews/leetcode/easy/merge-two-sorted-lists/tests/merge-two-sorted-lists.test.js
================================================
import { describe, it, expect } from 'vitest';
import { mergeTwoLists, ListNode } from '../merge-two-sorted-lists';
function buildList(nums) {
if (nums.length === 0) {
return null;
}
let head = new ListNode(nums[0]);
let node = head;
let nextNode;
for (let i = 1; i < nums.length; i++) {
nextNode = new ListNode(nums[i]);
node.next = nextNode;
node = node.next;
}
return head;
}
describe('mergeTwoLists', () => {
it('', () => {
const list1 = buildList([1, 2, 4]);
const list2 = buildList([1, 3, 4]);
const result = buildList([1, 1, 2, 3, 4, 4]);
expect(mergeTwoLists(list1, list2)).toEqual(result);
});
it('', () => {
const list1 = buildList([]);
const list2 = buildList([]);
const result = buildList([]);
expect(mergeTwoLists(list1, list2)).toEqual(result);
});
it('', () => {
const list1 = buildList([]);
const list2 = buildList([0]);
const result = buildList([0]);
expect(mergeTwoLists(list1, list2)).toEqual(result);
});
});
================================================
FILE: coding_interviews/leetcode/easy/merge_strings_alternately/merge_strings_alternately.py
================================================
# https://leetcode.com/problems/merge-strings-alternately/
def mergeAlternately(word1, word2):
smallest_length = min(len(word1), len(word2))
letters = []
for index in range(smallest_length):
letters.append(word1[index])
letters.append(word2[index])
if len(word1) > len(word2):
biggest_word = word1
else:
biggest_word = word2
return ''.join(letters) + biggest_word[smallest_length:]
================================================
FILE: coding_interviews/leetcode/easy/merge_trees.py
================================================
'''
https://leetcode.com/problems/merge-two-binary-trees/description/
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree
3
/ \
4 5
/ \ \
5 4 7
'''
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def merge_trees(t1, t2):
if not t1 and not t2: return None
new_node = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
new_node.left = merge_trees(t1 and t1.left, t2 and t2.left)
new_node.right = merge_trees(t1 and t1.right, t2 and t2.right)
return new_node
================================================
FILE: coding_interviews/leetcode/easy/merge_two_lists.py
================================================
# https://leetcode.com/problems/merge-two-sorted-lists/description/
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def merge_two_lists(l1, l2):
if l1 == None and l2 == None:
return l1
elif l1 == None:
return l2
elif l2 == None:
return l1
else:
n = root = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
n.next = l1
l1 = l1.next
else:
n.next = l2
l2 = l2.next
n = n.next
if l1:
n.next = l1
if l2:
n.next = l2
return root.next
================================================
FILE: coding_interviews/leetcode/easy/middle-of-the-linked-list/middle-of-the-linked-list-fast-slow.js
================================================
function middleNode(head) {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
================================================
FILE: coding_interviews/leetcode/easy/middle-of-the-linked-list/middle-of-the-linked-list.js
================================================
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
head = [1,2,3,4,5] => n = 5 => 5 / 2 => 2.5 => 2
[3,4,5]
head = [1] => n = 1 => 1 / 2 => 0.5 => 0
[1]
head = [1,2,3,4,5,6] => n = 6 => 6 / 2 => 3
[4,5,6]
*/
function getNodeCount(node, count) {
return node ? getNodeCount(node.next, count + 1) : count;
}
function getNode(node, index) {
return index ? getNode(node.next, index - 1) : node;
}
function middleNode(head) {
let count = getNodeCount(head, 0);
let middleIndex = Math.floor(count / 2);
return getNode(head, middleIndex);
}
================================================
FILE: coding_interviews/leetcode/easy/min-max-game/min-max-game.js
================================================
function minMaxGame(nums) {
while (nums.length > 1) {
let newNums = [];
let middleIndex = nums.length / 2;
for (let i = 0; i < middleIndex; i++) {
if (i % 2 === 0) newNums.push(Math.min(nums[2 * i], nums[2 * i + 1]));
else newNums.push(Math.max(nums[2 * i], nums[2 * i + 1]));
}
nums = newNums;
}
return nums;
}
================================================
FILE: coding_interviews/leetcode/easy/minimize-string-length/minimize-string-length.js
================================================
// https://leetcode.com/problems/minimize-string-length
function minimizedStringLength(s) {
let set = new Set();
for (let char of s) {
set.add(char);
}
return set.size;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-absolute-difference/minimum-absolute-difference.js
================================================
// https://leetcode.com/problems/minimum-absolute-difference
const minimumAbsDifference = (arr) => {
// runtime: O(NlogN)
// space: O(N)
let minDifference = Infinity;
const differenceToPairs = {};
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length - 1; i++) {
const num1 = arr[i];
const num2 = arr[i + 1];
const currentDifference = num2 - num1;
if (differenceToPairs[currentDifference]) {
differenceToPairs[currentDifference].push([num1, num2]);
} else {
differenceToPairs[currentDifference] = [[num1, num2]];
}
minDifference = Math.min(minDifference, currentDifference);
}
return differenceToPairs[minDifference];
};
================================================
FILE: coding_interviews/leetcode/easy/minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.js
================================================
function getMinimumDifference(root, rootVal = Infinity) {
if (!root) return Infinity;
return Math.min(
Math.abs(root.val - rootVal),
getMinimumDifference(root.left, root.val),
getMinimumDifference(root.right, root.val)
);
}
// ===============================================================
function traverse(node, list) {
if (!node) return null;
traverse(node.left, list);
list.push(node.val);
traverse(node.right, list);
}
function diff(list) {
let minDiff = Infinity;
let previous = list[0];
for (let index = 1; index < list.length; index++) {
minDiff = Math.min(list[index] - previous, minDiff);
previous = list[index];
}
return minDiff;
}
function getMinimumDifference(root) {
let list = [];
traverse(root, list);
return diff(list);
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-bit-flips-to-convert-number/minimum-bit-flips-to-convert-number.js
================================================
function toBinary(number) {
const binary = [];
while (number) {
binary.push((number % 2).toString());
number = Math.floor(number / 2);
}
return binary;
}
export function minBitFlips(start, goal) {
const startBinary = toBinary(start);
const goalBinary = toBinary(goal);
const greatestLength =
startBinary.length > goalBinary.length
? startBinary.length
: goalBinary.length;
let flips = 0;
for (let i = 0; i < greatestLength; i++) {
const startBit = startBinary[i] || '0';
const goalBit = goalBinary[i] || '0';
if (startBit !== goalBit) {
flips++;
}
}
return flips;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-bit-flips-to-convert-number/tests/minimum-bit-flips-to-convert-number.test.js
================================================
import { describe, expect, it } from 'vitest';
import { minBitFlips } from '../minimum-bit-flips-to-convert-number';
describe('minBitFlips', () => {
it('', () => {
expect(minBitFlips(10, 7)).toEqual(3);
});
it('', () => {
expect(minBitFlips(1, 16)).toEqual(2);
});
it('', () => {
expect(minBitFlips(3, 4)).toEqual(3);
});
});
================================================
FILE: coding_interviews/leetcode/easy/minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.js
================================================
function minCostToMoveChips(positions) {
let evenCount = 0;
let oddCount = 0;
for (let position of positions) {
if (position % 2 === 0) evenCount++;
else oddCount++;
}
return Math.min(evenCount, oddCount);
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.js
================================================
// https://leetcode.com/problems/minimum-depth-of-binary-tree
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
function minDepth(node, depth = 1) {
if (!node) return 0;
if (!node.left && !node.right) return depth;
if (!node.left) return minDepth(node.right, depth + 1);
if (!node.right) return minDepth(node.left, depth + 1);
return Math.min(
minDepth(node.left, depth + 1),
minDepth(node.right, depth + 1)
);
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.js
================================================
function traverse(node, list) {
if (!node) return;
traverse(node.left, list);
list.push(node.val);
traverse(node.right, list);
}
function getMinDiff(list) {
let minDiff = Infinity;
let previous = list[0];
for (let index = 1; index < list.length; index++) {
if (list[index] - previous < minDiff) minDiff = list[index] - previous;
previous = list[index];
}
return minDiff;
}
function minDiffInBST(root) {
let list = [];
traverse(root, list);
return getMinDiff(list);
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-number-game/minimum-number-game.js
================================================
// https://leetcode.com/problems/minimum-number-game
function numberGame(nums) {
let arr = [];
nums.sort((a, b) => a - b);
for (let index = 0; index < nums.length; index += 2) {
let alice = nums[index];
let bob = nums[index + 1];
arr.push(bob);
arr.push(alice);
}
return arr;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-number-of-moves-to-seat-everyone/minimum-number-of-moves-to-seat-everyone.js
================================================
function sort(nums) {
return [...nums].sort((a, b) => a - b);
}
export function minMovesToSeat(seats, students) {
const sortedSeats = sort(seats);
const sortedStudents = sort(students);
const N = seats.length;
let moves = 0;
for (let i = 0; i < N; i++) {
moves += Math.abs(sortedSeats[i] - sortedStudents[i]);
}
return moves;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-number-of-moves-to-seat-everyone/tests/minimum-number-of-moves-to-seat-everyone.test.js
================================================
import { describe, it, expect } from 'vitest';
import { minMovesToSeat } from '../minimum-number-of-moves-to-seat-everyone';
describe('minMovesToSeat', () => {
it('', () => {
expect(minMovesToSeat([3, 1, 5], [2, 7, 4])).toEqual(4);
});
it('', () => {
expect(minMovesToSeat([4, 1, 5, 9], [1, 3, 2, 6])).toEqual(7);
});
it('', () => {
expect(minMovesToSeat([2, 2, 6, 6], [1, 3, 2, 6])).toEqual(4);
});
});
================================================
FILE: coding_interviews/leetcode/easy/minimum-number-of-operations-to-convert-time/minimum-number-of-operations-to-convert-time.js
================================================
function toMinutes(stringTime) {
const [hour, minutes] = stringTime.split(':');
return Number(hour) * 60 + Number(minutes);
}
function convertTime(current, correct) {
let count = 0;
let minutes = toMinutes(correct) - toMinutes(current);
while (minutes) {
if (minutes >= 60) minutes -= 60;
else if (minutes >= 15) minutes -= 15;
else if (minutes >= 5) minutes -= 5;
else minutes -= 1;
count++;
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-string-length-after-removing-substrings/minimum-string-length-after-removing-substrings.js
================================================
// https://leetcode.com/problems/minimum-string-length-after-removing-substrings
function minLength(s) {
while (true) {
let found = false;
for (let index = 0; index < s.length - 1; index++) {
let slice = s.slice(index, index + 2);
if (['AB', 'CD'].includes(slice)) {
s = s.slice(0, index) + s.slice(index + 2);
found = true;
break;
}
}
if (!found) break;
}
return s.length;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-subsequence-in-non-increasing-order/minimum-subsequence-in-non-increasing-order.js
================================================
function sum(nums) {
return nums.reduce((sumOfNums, num) => sumOfNums + num, 0);
}
function minSubsequence(nums) {
const result = [];
const sortedNums = [...nums].sort((a, b) => a - b);
let index = nums.length - 1;
let sumOfNums = sum(sortedNums);
let otherHalfSum = 0;
while (index >= 0 && otherHalfSum <= sumOfNums) {
const num = sortedNums[index];
result.push(num);
sumOfNums -= num;
otherHalfSum += num;
index--;
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-sum/minimum-sum.js
================================================
/*
You are given a positive integer num consisting of exactly four digits.
Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2,
and all the digits found in num must be used.
For example, given num = 2932, you have the following digits:
two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
Return the minimum possible sum of new1 and new2.
# Example 1:
Input: num = 2932
Output: 52
Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.
The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.
# Example 2:
Input: num = 4009
Output: 13
Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc.
The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.
*/
// 2932 => 2, 9, 3, 2 => 2, 2 => 29, 23
function getAllDigits(number) {
const stringNumber = number.toString();
const digits = [];
for (let i = 0; i < stringNumber.length; i++) {
digits.push(Number(stringNumber[i]));
}
return digits;
}
function sort(digits) {
return digits.sort((digit1, digit2) => digit1 - digit2);
}
function minimumSum(number) {
const digits = getAllDigits(number);
const sortedDigits = sort(digits);
const [digit1, digit2, digit3, digit4] = sortedDigits;
return digit1 * 10 + digit3 + (digit2 * 10 + digit4);
}
console.log(minimumSum(2932), 52);
console.log(minimumSum(4009), 13);
function altMinimunSum(number) {
const digits = number.toString().split('').sort();
return Number(digits[0] + digits[2]) + Number(digits[1] + digits[3]);
}
console.log(altMinimunSum(2932), 52);
console.log(altMinimunSum(4009), 13);
================================================
FILE: coding_interviews/leetcode/easy/minimum-sum-of-mountain-triplets-i/minimum-sum-of-mountain-triplets-i.js
================================================
// https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i
function minimumSum(nums) {
let min = Infinity;
for (let i = 0; i < nums.length - 2; i++) {
for (let j = i + 1; j < nums.length - 1; j++) {
for (let k = j + 1; k < nums.length; k++) {
if (nums[i] < nums[j] && nums[k] < nums[j]) {
min = Math.min(min, nums[i] + nums[j] + nums[k]);
}
}
}
}
return min == Infinity ? -1 : min;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum-time-to-type-word-using-special-typewriter/minimum-time-to-type-word-using-special-typewriter.js
================================================
// https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter
const minTimeToType = (word) => {
const wordLength = word.length;
let currentIndex = 0;
let moves = wordLength;
for (let i = 0; i < wordLength; i++) {
const letter = word[i];
const charCode = letter.charCodeAt() - 97;
const firstDistance = Math.abs(charCode - currentIndex);
const secondDistance =
charCode > currentIndex
? currentIndex + 26 - charCode
: charCode + 26 - currentIndex;
const minimumDistance = Math.min(firstDistance, secondDistance);
moves += minimumDistance;
currentIndex = charCode;
}
return moves;
};
================================================
FILE: coding_interviews/leetcode/easy/minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.js
================================================
function getMinValue(nums) {
let min = Infinity;
let sum = 0;
for (let num of nums) {
sum += num;
min = Math.min(min, sum);
}
return min;
}
function minStartValue(nums) {
const minValue = getMinValue(nums);
const result = 1 - minValue;
return result >= 1 ? result : 1;
}
================================================
FILE: coding_interviews/leetcode/easy/minimum_operations_to_make_the_array_increasing/minimum_operations_to_make_the_array_increasing.py
================================================
# https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing
def min_operations(nums):
previous_num = nums[0]
operations = 0
for index, num in enumerate(nums[1:]):
if num <= previous_num:
new_num = previous_num - num + 1
operations += new_num
nums[index + 1] += new_num
previous_num = nums[index + 1]
return operations
def min_operations(nums):
prev, ops = 0, 0
for num in nums:
if num <= prev:
prev += 1
ops += prev - num
else:
prev = num
return ops
================================================
FILE: coding_interviews/leetcode/easy/missing-number/missing-number.js
================================================
function buildHashmap(nums) {
const hashmap = new Map();
for (let num of nums) {
hashmap.set(num, true);
}
return hashmap;
}
function getMissingNumber(numsLength, hashmap) {
for (let i = 0; i <= numsLength; i++) {
if (!hashmap.has(i)) return i;
}
}
function missingNumber(nums) {
const hashmap = buildHashmap(nums);
return getMissingNumber(nums.length, hashmap);
}
================================================
FILE: coding_interviews/leetcode/easy/monotonic-array/monotonic-array.js
================================================
function isMonotonic(nums) {
if (nums.length === 1) return true;
let isIncreasing;
let previous = nums[0];
for (let index = 1; index < nums.length; index++) {
if (nums[index] === previous) {
previous = nums[index];
continue;
}
if (isIncreasing === undefined) {
isIncreasing = previous <= nums[index];
}
if (isIncreasing && nums[index] < previous) return false;
if (!isIncreasing && nums[index] > previous) return false;
previous = nums[index];
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/most-words-found/most-words-found.js
================================================
/*
A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
You are given an array of strings sentences, where each sentences[i] represents a single sentence.
Return the maximum number of words that appear in a single sentence.
# Example 1:
Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
Explanation:
- The first sentence, "alice and bob love leetcode", has 5 words in total.
- The second sentence, "i think so too", has 4 words in total.
- The third sentence, "this is great thanks very much", has 6 words in total.
Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.
# Example 2:
Input: sentences = ["please wait", "continue to fight", "continue to win"]
Output: 3
Explanation: It is possible that multiple sentences contain the same number of words.
In this example, the second and third sentences (underlined) have the same number of words.
*/
function mostWordsFound(sentences = []) {
return Math.max(...sentences.map((sentence) => sentence.split(' ').length));
}
console.log(
mostWordsFound([
'alice and bob love leetcode',
'i think so too',
'this is great thanks very much',
]),
6
);
console.log(
mostWordsFound(['please wait', 'continue to fight', 'continue to win']),
3
);
================================================
FILE: coding_interviews/leetcode/easy/move-zeroes/move-zeroes-in-place.js
================================================
function moveZeroes(nums) {
let zeroesCount = 0;
let inPlaceIndex = 0;
for (let num of nums) {
if (num) {
nums[inPlaceIndex] = num;
inPlaceIndex++;
} else {
zeroesCount++;
}
}
while (zeroesCount) {
nums[nums.length - zeroesCount] = 0;
zeroesCount--;
}
}
================================================
FILE: coding_interviews/leetcode/easy/move-zeroes/move-zeroes.js
================================================
function moveZeroes(nums) {
let numsWithZerosAtTheEnd = [];
let zeroCount = 0;
for (let num of nums) {
if (num) {
numsWithZerosAtTheEnd.push(num);
} else {
zeroCount++;
}
}
while (zeroCount) {
numsWithZerosAtTheEnd.push(0);
zeroCount--;
}
return numsWithZerosAtTheEnd;
}
================================================
FILE: coding_interviews/leetcode/easy/n_ary_tree_postorder_traversal/n_ary_tree_postorder_traversal.py
================================================
# https://leetcode.com/problems/n-ary-tree-postorder-traversal
result = []
def postorder(root):
if root is None: return []
for node in root.children:
postorder(node)
result.append(root.val)
return result
================================================
FILE: coding_interviews/leetcode/easy/n_ary_tree_preorder_traversal/n_ary_tree_preorder_traversal.py
================================================
# https://leetcode.com/problems/n-ary-tree-postorder-traversal
result = []
def preorder(root):
if root is None: return []
result.append(root.val)
for node in root.children:
preorder(node)
return result
================================================
FILE: coding_interviews/leetcode/easy/n_repeated_element_in_size_2n_array/n_repeated_element_in_size_2n_array.py
================================================
# https://leetcode.com/problems/n-repeated-element-in-size-2n-array/
'''
In a array A of size 2N, there are N+1 unique elements,
and exactly one of these elements is repeated N times.
Return the element repeated N times.
Example 1:
Input: [1,2,3,3]
Output: 3
Example 2:
Input: [2,1,2,5,3,2]
Output: 2
Example 3:
Input: [5,1,5,2,5,3,5,4]
Output: 5
'''
def n_repeated_element_in_size_2n_array(A):
map_counter = {}
for number in A:
if number in map_counter:
map_counter[number] += 1
return number
else:
map_counter[number] = 1
data_tests = [
([1, 2, 3, 3], 3),
([2, 1, 2, 5, 3, 2], 2),
([5, 1, 5, 2, 5, 3, 5, 4], 5)
]
for numbers, expected in data_tests:
result = n_repeated_element_in_size_2n_array(numbers)
print(result, expected == result)
================================================
FILE: coding_interviews/leetcode/easy/neither-minimum-nor-maximum/neither-minimum-nor-maximum-on.js
================================================
// https://leetcode.com/problems/neither-minimum-nor-maximum
function findNonMinOrMax(nums) {
let min = Infinity,
max = -Infinity;
for (num of nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
for (let num of nums) {
if (num !== min && num !== max) {
return num;
}
}
return -1;
}
================================================
FILE: coding_interviews/leetcode/easy/neither-minimum-nor-maximum/neither-minimum-nor-maximum.js
================================================
// https://leetcode.com/problems/neither-minimum-nor-maximum
function findNonMinOrMax(nums) {
return nums.length > 2 ? nums.sort((a, b) => a - b)[1] : -1;
}
================================================
FILE: coding_interviews/leetcode/easy/next-greater-element-i/next-greater-element-i-optimized.js
================================================
function peek(stack) {
return stack[stack.length - 1];
}
function isEmpty(stack) {
return stack.length === 0;
}
export function nextGreaterElement(nums1, nums2) {
const stack = [];
const hashmap = new Map();
for (let num of nums2) {
while (!isEmpty(stack) && num > peek(stack)) {
hashmap.set(stack.pop(), num);
}
stack.push(num);
}
while (!isEmpty(stack)) {
hashmap.set(stack.pop(), -1);
}
const result = [];
for (let num of nums1) {
if (hashmap.has(num)) {
result.push(hashmap.get(num));
} else {
result.push(-1);
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/next-greater-element-i/next-greater-element-i.js
================================================
export function nextGreaterElement(nums1, nums2) {
const result = [];
for (let num1 of nums1) {
let foundNumber = false;
let foundNextGreaterElement = false;
for (let num2 of nums2) {
if (num1 === num2) {
foundNumber = true;
}
if (foundNumber && num2 > num1) {
result.push(num2);
foundNextGreaterElement = true;
break;
}
}
if (!foundNextGreaterElement) {
result.push(-1);
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/next-greater-element-i/tests/next-greater-element-i-optimized.test.js
================================================
import { describe, expect, it } from 'vitest';
import { nextGreaterElement } from '../next-greater-element-i-optimized';
describe('nextGreaterElement', () => {
it('', () => {
expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])).toEqual([-1, 3, -1]);
});
it('', () => {
expect(nextGreaterElement([2, 4], [1, 2, 3, 4])).toEqual([3, -1]);
});
it('', () => {
expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2, 5])).toEqual([5, 3, 5]);
});
it('', () => {
expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1])).toEqual([5, -1, -1]);
});
it('', () => {
expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1, 6])).toEqual([
5, 6, 6,
]);
});
it('', () => {
expect(
nextGreaterElement([9, 8, 7, 3, 2, 1, 6], [9, 8, 7, 3, 2, 1, 6])
).toEqual([-1, -1, -1, 6, 6, 6, -1]);
});
});
================================================
FILE: coding_interviews/leetcode/easy/next-greater-element-i/tests/next-greater-element-i.test.js
================================================
import { describe, expect, it } from 'vitest';
import { nextGreaterElement } from '../next-greater-element-i';
describe('nextGreaterElement', () => {
it('', () => {
expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])).toEqual([-1, 3, -1]);
});
it('', () => {
expect(nextGreaterElement([2, 4], [1, 2, 3, 4])).toEqual([3, -1]);
});
it('', () => {
expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2, 5])).toEqual([5, 3, 5]);
});
it('', () => {
expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1])).toEqual([5, -1, -1]);
});
it('', () => {
expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1, 6])).toEqual([
5, 6, 6,
]);
});
});
================================================
FILE: coding_interviews/leetcode/easy/num_unique_emails/num_unique_emails.py
================================================
def num_unique_emails(emails):
unique_emails = set()
for email in emails:
[local, domain] = email.split('@')
splitted_local = local.split('+')
new_local = ''.join(splitted_local[0].split('.'))
unique_emails.add(new_local + '@' + domain)
return len(unique_emails)
================================================
FILE: coding_interviews/leetcode/easy/number-of-1-bits/number-of-1-bits.js
================================================
function hammingWeight(n) {
let sum = 0;
while (n != 0) {
sum += n & 1;
n = n >>> 1;
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-arithmetic-triplets/number-of-arithmetic-triplets.js
================================================
function buildMap(nums) {
const hashmap = new Map();
for (let num of nums) {
hashmap.set(num, num);
}
return hashmap;
}
function arithmeticTriplets(nums, diff) {
let hashmap = buildMap(nums);
let counter = 0;
for (let index = 0; index < nums.length - 2; index++) {
const number = nums[index] + diff;
const anotherNumber = number + diff;
if (hashmap.has(number) && hashmap.has(anotherNumber)) {
counter++;
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-common-factors/number-of-common-factors.js
================================================
function commonFactors(a, b) {
let minValue = Math.min(a, b);
let counter = 0;
for (let num = 1; num <= minValue; num++) {
if (a % num === 0 && b % num === 0) counter++;
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-employees-who-met-the-target/number-of-employees-who-met-the-target.js
================================================
function numberOfEmployeesWhoMetTarget(hours, target) {
let count = 0;
for (let hour of hours) {
if (hour >= target) count++;
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-even-and-odd-bits/number-of-even-and-odd-bits.js
================================================
function toBinary(n) {
const binary = [];
while (n > 0) {
binary.push(n % 2);
n = Math.floor(n / 2);
}
return binary;
}
function isEven(n) {
return n % 2 === 0;
}
function isOdd(n) {
return n % 2 !== 0;
}
function evenOddBit(n) {
let binary = toBinary(n);
let even = 0;
let odd = 0;
for (let index = 0; index < binary.length; index++) {
if (isEven(index) && binary[index]) even++;
if (isOdd(index) && binary[index]) odd++;
}
return [even, odd];
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-lines-to-write-string/number-of-lines-to-write-string.js
================================================
// https://leetcode.com/problems/number-of-lines-to-write-string
function toWidthsIndex(char) {
return char.charCodeAt() - 97;
}
function numberOfLines(widths, s) {
let output = [1, 0];
for (let char of s) {
let width = widths[toWidthsIndex(char)];
if (output[1] + width <= 100) {
output[1] = output[1] + width;
} else {
output[0]++;
output[1] = width;
}
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-senior-citizens/number-of-senior-citizens.js
================================================
function countSeniors(details) {
let count = 0;
for (let detail of details) {
if (Number(detail.slice(11, 13)) > 60) {
count++;
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/number-of-senior-citizens/one-liner-number-of-senior-citizens.js
================================================
function countSeniors(details) {
return details
.filter((detail) => Number(detail.slice(11, 13)) > 60)
.length;
};
================================================
FILE: coding_interviews/leetcode/easy/number-of-strings-that-appear-as-substrings-in-word/number-of-strings-that-appear-as-substrings-in-word.js
================================================
const isPatternInWord = (pattern, word) => {
const patternLength = pattern.length;
let hasPattern = false;
for (let i = 0; i + patternLength <= word.length; i++) {
console.log(word.substring(i, i + patternLength));
if (word.substring(i, i + patternLength) === pattern) {
hasPattern = true;
}
}
return hasPattern;
};
const numOfStrings = (patterns, word) => {
let count = 0;
patterns.forEach((pattern) => {
if (isPatternInWord(pattern, word)) {
count++;
}
});
return count;
};
const result = numOfStrings(['a', 'abc', 'bc', 'd'], 'abc');
console.log('result', result);
================================================
FILE: coding_interviews/leetcode/easy/number-of-unequal-triplets-in-array/number-of-unequal-triplets-in-array.js
================================================
function unequalTriplets(nums) {
let counter = 0;
for (let i = 0; i < nums.length - 2; i++) {
for (let j = i + 1; j < nums.length - 1; j++) {
for (let k = j + 1; k < nums.length; k++) {
let iNum = nums[i];
let jNum = nums[j];
let kNum = nums[k];
if (iNum !== jNum && iNum !== kNum && jNum !== kNum) counter++;
}
}
}
return counter;
}
================================================
FILE: coding_interviews/leetcode/easy/number_complement.py
================================================
'''
https://leetcode.com/problems/number-complement/description/
Input: 5
Output: 2
Input: 1
Output: 0
'''
def to_binary(num):
binary_num = ''
copy_num = num
while copy_num > 0:
binary_num += str(copy_num % 2)
copy_num /= 2
return binary_num
def to_binary_complement(binary_num):
return ''.join(['1' if binary == '0' else '0' for binary in binary_num])
def to_complement(complement_binary_num):
return sum([pow(2, index) for index, binary in enumerate(complement_binary_num) if binary == '1'])
def find_complement(num):
binary_num = to_binary(num)
complement_binary_num = to_binary_complement(binary_num)
return to_complement(complement_binary_num)
print(find_complement(5) == 2)
print(find_complement(1) == 0)
print(find_complement(8) == 7)
================================================
FILE: coding_interviews/leetcode/easy/number_of_good_pairs/number_of_good_pairs.py
================================================
def factorial(n):
if n <= 1: return 1
return factorial(n - 1) * n
def permutation(n, r):
return factorial(n) // (factorial(n - r) * factorial(r))
def number_of_good_pairs(nums):
nums_counter = {}
for num in nums:
if num in nums_counter:
nums_counter[num] += 1
else:
nums_counter[num] = 1
counter = 0
for num, num_counter in nums_counter.items():
if num_counter > 1:
counter += permutation(num_counter, 2)
return counter
# ------------------------------------------------------------
from math import factorial
def permutation(n, r):
return factorial(n) // (factorial(n - r) * factorial(r))
def number_of_good_pairs(nums):
nums_counter = {}
for num in nums:
if num in nums_counter:
nums_counter[num] += 1
else:
nums_counter[num] = 1
counter = 0
for num, num_counter in nums_counter.items():
if num_counter > 1:
counter += permutation(num_counter, 2)
return counter
# ------------------------------------------------------------
def number_of_good_pairs(nums):
nums_counter = {}
counter = 0
for num in nums:
if num in nums_counter:
counter += nums_counter[num]
nums_counter[num] += 1
else:
nums_counter[num] = 1
return counter
# ------------------------------------------------------------
from collections import Counter
def number_of_good_pairs(nums):
nums_counter = Counter()
counter = 0
for num in nums:
counter += nums_counter[num]
nums_counter[num] += 1
return counter
================================================
FILE: coding_interviews/leetcode/easy/number_of_recent_calls/number_of_recent_calls.py
================================================
# https://leetcode.com/problems/number-of-recent-calls
class RecentCounter:
def __init__(self):
self.requests = []
def ping(self, t: int) -> int:
self.requests.append(t)
initial_time = t - 3000
counter = 0
for request in self.requests:
if request >= initial_time and request <= t:
counter += 1
return counter
class RecentCounter:
def __init__(self):
self.requests = deque()
def ping(self, t: int) -> int:
self.requests.append(t)
while self.requests[0] < t - 3000:
self.requests.popleft()
return len(self.requests)
================================================
FILE: coding_interviews/leetcode/easy/number_of_students/number_of_students.py
================================================
def busy_student(start_time, end_time, query_time):
number_of_students = 0
for index in range(len(start_time)):
start, end = start_time[index], end_time[index]
if query_time >= start and query_time <= end:
number_of_students += 1
return number_of_students
def busy_student(start_time, end_time, query_time):
number_of_students = 0
for start, end in zip(start_time, end_time):
if query_time >= start and query_time <= end:
number_of_students += 1
return number_of_students
================================================
FILE: coding_interviews/leetcode/easy/odd-string-difference/odd-string-difference.js
================================================
function toCode(char) {
return char.charCodeAt() - 97;
}
function buildDiffIntegerArray(word) {
let diffIntegerArray = [];
let previous = word[0];
for (let index = 1; index < word.length; index++) {
let current = word[index];
diffIntegerArray.push(toCode(current) - toCode(previous));
previous = current;
}
return diffIntegerArray;
}
function joinIntegersString(diff) {
return diff.map((diffNum) => diffNum.toString()).join('*');
}
function oddString(words) {
let hashmap = new Map();
for (let word of words) {
let key = joinIntegersString(buildDiffIntegerArray(word));
if (hashmap.has(key)) {
hashmap.set(key, [hashmap.get(key)[0] + 1, word]);
} else {
hashmap.set(key, [1, word]);
}
}
for (let [_, [count, word]] of hashmap.entries()) {
if (count === 1) {
return word;
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/odd_in_matrix/odd_in_matrix.py
================================================
def init_matrix(rows, columns):
return [[0 for _ in range(columns)] for _ in range(rows)]
def odd_cells(n, m, indices):
matrix = init_matrix(n, m)
for [ri, ci] in indices:
for column in range(m):
matrix[ri][column] += 1
for row in range(n):
matrix[row][ci] += 1
odds = 0
for row in range(n):
for column in range(m):
if matrix[row][column] % 2 != 0:
odds += 1
return odds
================================================
FILE: coding_interviews/leetcode/easy/partition_labels.py
================================================
'''
https://leetcode.com/problems/partition-labels/description/
Input: S = "ababcbacadefegdehijhklij"
Output: [9, 7, 8]
Input: S = "abc"
Output: [1, 1, 1]
Input: S = "abbaa"
Output: [5]
'''
def partition_labels(S):
partitions = []
start_index = 0
last_index = S.rfind(S[0])
for i, c in enumerate(S, 1):
if i == len(S):
partitions.append(S[start_index:])
elif last_index == i - 1:
partitions.append(S[start_index:i])
start_index = i
last_index = S.rfind(S[i])
elif S.rfind(S[i]) > last_index:
last_index = S.rfind(S[i])
return [len(partition) for partition in partitions]
print(partition_labels("ababcbacadefegdehijhklij") == [9, 7, 8])
print(partition_labels("abc") == [1, 1, 1])
print(partition_labels("abbaa") == [5])
================================================
FILE: coding_interviews/leetcode/easy/pascals-triangle/pascals-triangle.js
================================================
function generate(numRows) {
let triangle = [[1]];
for (let row = 1; row < numRows; row++) {
let triangleRow = [];
for (let index = 0; index <= row; index++) {
const num1 = index - 1 >= 0 ? triangle[row - 1][index - 1] : 0;
const num2 =
index < triangle[row - 1].length ? triangle[row - 1][index] : 0;
triangleRow.push(num1 + num2);
}
triangle.push(triangleRow);
}
return triangle;
}
================================================
FILE: coding_interviews/leetcode/easy/path-sum/path-sum.js
================================================
function hasPathSum(root, targetSum, sum = 0) {
if (!root) {
return false;
}
if (!root.left && !root.right) {
return sum + root.val === targetSum;
}
return (
hasPathSum(root.left, targetSum, sum + root.val) ||
hasPathSum(root.right, targetSum, sum + root.val)
);
}
================================================
FILE: coding_interviews/leetcode/easy/peak_index_mountain.py
================================================
'''
https://leetcode.com/problems/peak-index-in-a-mountain-array/description/
Input: [0, 1, 0]
Output: 1
Input: [0, 2, 1, 0]
Output: 1
'''
def peak_index_in_mountain_array(A):
peak = A[0]
peak_index = 0
for index, mountain_height in enumerate(A):
if mountain_height > peak:
peak_index = index
peak = mountain_height
return peak_index
print(peak_index_in_mountain_array([0, 1, 0]) == 1)
print(peak_index_in_mountain_array([0, 2, 1, 0]) == 1)
================================================
FILE: coding_interviews/leetcode/easy/percentage-of-letter-in-string/percentage-of-letter-in-string.js
================================================
function percentageLetter(s, letter) {
let counter = new Map();
for (let char of s) {
if (counter.has(char)) {
counter.set(char, counter.get(char) + 1);
} else {
counter.set(char, 1);
}
}
let letterCount = counter.has(letter) ? counter.get(letter) : 0;
return Math.floor((letterCount / s.length) * 100);
}
================================================
FILE: coding_interviews/leetcode/easy/plus_one/plus_one.js
================================================
// https://leetcode.com/problems/plus-one/
function add_one(digits) {
return plus_one(digits, 1);
}
function plus_one(digits, inc) {
if (digits.length == 0 && inc > 0) {
return [1];
}
if (digits.length == 0 && inc == 0) {
return [];
}
let new_inc;
let last_digit;
last_digit = digits[digits.length - 1];
last_digit = last_digit + inc;
if (last_digit == 10) {
new_inc = 1;
} else {
new_inc = 0;
}
return plus_one(
digits.slice(0, digits.length - 1),
new_inc
).concat([last_digit % 10]);
}
console.log(add_one([1, 2, 3])) // [1, 2, 4]
console.log(add_one([4, 3, 2, 1])) // [4, 3, 2, 2]
console.log(add_one([1, 2, 9])) // [1, 3, 0]
console.log(add_one([1, 9, 9])) // [2, 0, 0]
console.log(add_one([9, 9, 9])) // [1, 0, 0, 0]
console.log(add_one([1, 0, 0, 0, 0])) // [1, 0, 0, 0, 1]
================================================
FILE: coding_interviews/leetcode/easy/plus_one/plus_one.py
================================================
# https://leetcode.com/problems/plus-one/
def add_one(digits):
return plus_one(digits, 1)
def plus_one(digits, inc):
if digits == [] and inc > 0:
return [1]
if digits == [] and inc == 0:
return []
last_digit = digits[-1]
last_digit = last_digit + inc
if last_digit == 10:
new_inc = 1
else:
new_inc = 0
return plus_one(digits[0:-1], new_inc) + [last_digit % 10]
print(add_one([1, 2, 3])) # [1, 2, 4]
print(add_one([4, 3, 2, 1])) # [4, 3, 2, 2]
print(add_one([1, 2, 9])) # [1, 3, 0]
print(add_one([1, 9, 9])) # [2, 0, 0]
print(add_one([9, 9, 9])) # [1, 0, 0, 0]
print(add_one([1, 0, 0, 0, 0])) # [1, 0, 0, 0, 1]
================================================
FILE: coding_interviews/leetcode/easy/points-that-intersect-with-cars/points-that-intersect-with-cars.js
================================================
// https://leetcode.com/problems/points-that-intersect-with-cars
function numberOfPoints(nums) {
let map = new Map();
let points = 0;
for ([start, end] of nums) {
for (let num = start; num <= end; num++) {
if (!map.has(num)) {
points++;
map.set(num, true);
}
}
}
return points;
}
================================================
FILE: coding_interviews/leetcode/easy/power-of-two/power-of-two.js
================================================
function isPowerOfTwo(n) {
if (n <= 0) {
return false;
}
while (n > 1) {
if (n % 2 !== 0) {
return false;
}
n /= 2;
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/prime-number-of-set-bits-in-binary-representation/prime-number-of-set-bits-in-binary-representation.js
================================================
// https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation
function toBinary(n) {
let binary = [];
while (n) {
binary.push((n % 2).toString());
n = Math.floor(n / 2);
}
return binary.join('');
}
function getNumberOfSetBits(binary) {
let count = 0;
for (let digit of binary) {
if (digit === '1') count++;
}
return count;
}
function isPrime(num) {
for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
if (num % i === 0) return false;
}
return num > 1;
}
function countPrimeSetBits(left, right) {
let count = 0;
for (let num = left; num <= right; num++) {
let binary = toBinary(num);
let setBits = getNumberOfSetBits(binary);
if (isPrime(setBits)) {
count++;
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/projection-area-of-3d-shapes/projection-area-of-3d-shapes.js
================================================
// https://leetcode.com/problems/projection-area-of-3d-shapes
function projectionArea(grid) {
let xy = 0;
let xz = 0;
let yz = 0;
for (let x = 0; x < grid.length; x++) {
for (let y = 0; y < grid[x].length; y++) {
if (grid[x][y] > 0) xy++;
}
}
for (let x = 0; x < grid.length; x++) {
let max = -Infinity;
for (let z = 0; z < grid[x].length; z++) {
max = Math.max(max, grid[x][z]);
}
xz += max;
}
let allAreas = [];
for (let y = 0; y < grid.length; y++) {
for (let z = 0; z < grid[y].length; z++) {
allAreas[z] = Math.max(allAreas[z] || 0, grid[y][z]);
}
}
yz = allAreas.reduce((sum, area) => sum + area, 0);
return xy + xz + yz;
}
================================================
FILE: coding_interviews/leetcode/easy/range_sum_of_bst/range_sum_of_bst.py
================================================
# https://leetcode.com/problems/range-sum-of-bst/submissions/
'''
Given the root node of a binary search tree,
return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
'''
def rangeSumBST(root, L, R):
left_sum = 0
right_sum = 0
root_sum = 0
if root.left is not None and root.val > L:
left_sum = rangeSumBST(root.left, L, R)
if root.right is not None and root.val < R:
right_sum = rangeSumBST(root.right, L, R)
if root.val >= L and root.val <= R:
root_sum = root.val
return root_sum + left_sum + right_sum
================================================
FILE: coding_interviews/leetcode/easy/rank-transform-of-an-array/rank-transform-of-an-array-less-memory.js
================================================
// https://leetcode.com/problems/rank-transform-of-an-array
/**
* [40,10,20,30]
* [10,20,30,40] => O(NlogN)
* {10: 1, 20: 2, 30: 3, 40: 4} => O(N), N = array size
* [4,1,2,3] => O(N)
* runtime: O(NlogN)
* space: O(N)
*/
function buildMap(set) {
let map = new Map();
let index = 1;
for (let num of set.values()) {
map.set(num, index);
index++;
}
return map;
}
function buildRank(arr, map) {
for (let index = 0; index < arr.length; index++) {
arr[index] = map.get(arr[index]);
}
return arr;
}
function arrayRankTransform(arr) {
const sortedSet = new Set([...arr].sort((a, b) => a - b));
const map = buildMap(sortedSet);
return buildRank(arr, map);
}
================================================
FILE: coding_interviews/leetcode/easy/rank-transform-of-an-array/rank-transform-of-an-array.js
================================================
// https://leetcode.com/problems/rank-transform-of-an-array
/**
* [40,10,20,30]
* [10,20,30,40] => O(NlogN)
* {10: 1, 20: 2, 30: 3, 40: 4} => O(N), N = array size
* [4,1,2,3] => O(N)
* runtime: O(NlogN)
* space: O(N)
*/
function buildMap(set) {
let map = new Map();
let index = 1;
for (let num of set.values()) {
map.set(num, index);
index++;
}
return map;
}
function buildRank(arr, map) {
let rank = [];
for (let num of arr) {
rank.push(map.get(num));
}
return rank;
}
function arrayRankTransform(arr) {
const sortedSet = new Set([...arr].sort((a, b) => a - b));
const map = buildMap(sortedSet);
return buildRank(arr, map);
}
================================================
FILE: coding_interviews/leetcode/easy/ransom-note/ransom-note.js
================================================
function canConstruct(ransomNote, magazine) {
let map = {};
for (let char of magazine) {
if (map[char]) {
map[char] += 1;
} else {
map[char] = 1;
}
}
for (let char of ransomNote) {
if (map[char]) {
map[char]--;
} else {
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/ransom_note/ransom_note.py
================================================
def can_construct(ransom_note, magazine):
if ransom_note == '':
return True
if magazine == '':
return False
letters_counter = {}
for letter in magazine:
if letter in letters_counter:
letters_counter[letter] += 1
else:
letters_counter[letter] = 1
for char in ransom_note:
if char not in letters_counter or letters_counter[char] == 0:
return False
letters_counter[char] -= 1
return True
================================================
FILE: coding_interviews/leetcode/easy/reduce_zero/reduce_zero.py
================================================
# https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
def reduce_number(num):
if num % 2 == 0:
return num / 2
else:
return num - 1
def number_of_steps(num):
counter = 0
while num:
counter += 1
num = reduce_number(num)
return counter
data_tests = [
(14, 6),
(8, 4)
]
for number, expected in data_tests:
result = number_of_steps(number)
print(result, expected == result)
================================================
FILE: coding_interviews/leetcode/easy/reformat-date/reformat-date.js
================================================
// https://leetcode.com/problems/reformat-date
function getDateInfo(date) {
let dateInfo = [];
let info = '';
for (let index = 0; index < date.length; index++) {
let char = date[index];
if (char === ' ') {
dateInfo.push(info);
info = '';
} else if (index === date.length - 1) {
dateInfo.push(info + char);
} else {
info += char;
}
}
return dateInfo;
}
const monthStringToNumber = {
Jan: '01',
Feb: '02',
Mar: '03',
Apr: '04',
May: '05',
Jun: '06',
Jul: '07',
Aug: '08',
Sep: '09',
Oct: '10',
Nov: '11',
Dec: '12',
};
function formatDay(day) {
return day.length === 1 ? `0${day}` : day;
}
function reformatDate(date) {
let [day, month, year] = getDateInfo(date);
let dateDay = '';
let dateMonth = monthStringToNumber[month];
for (let char of day) {
if (!Number.isNaN(Number(char))) {
dateDay += char;
}
}
return `${year}-${dateMonth}-${formatDay(dateDay)}`;
}
================================================
FILE: coding_interviews/leetcode/easy/reformat-phone-number/reformat-phone-number.js
================================================
function removeSpacesAndDashes(number) {
return number.replaceAll('-', '').replaceAll(' ', '');
}
function reformatNumber(number) {
let num = removeSpacesAndDashes(number);
let blocks = [];
let block = [];
let blockLimit = 2;
let numLength = num.length;
for (let index = 0; index < numLength; index++) {
if (block.length === 0) {
if (numLength - index === 2) {
blocks.push(num.slice(index));
break;
}
if (numLength - index === 4) {
blocks.push(num.slice(index, index + 2));
blocks.push(num.slice(index + 2));
break;
}
}
if (index === blockLimit) {
blockLimit = index + 3;
block.push(num[index]);
blocks.push(block.join(''));
block = [];
} else {
block.push(num[index]);
}
}
return blocks.join('-');
}
================================================
FILE: coding_interviews/leetcode/easy/relative-ranks/relative-ranks.js
================================================
function sortDesc(list) {
return list.sort((a, b) => b - a);
}
const mapper = {
0: 'Gold Medal',
1: 'Silver Medal',
2: 'Bronze Medal',
};
function buildHashmap(list) {
let hashmap = new Map();
for (let [index, item] of list.entries()) {
hashmap.set(item, mapper[index] || (index + 1).toString());
}
return hashmap;
}
function getRelativeRanks(score, hashmap) {
let rank = [];
for (let value of score) {
rank.push(hashmap.get(value));
}
return rank;
}
function findRelativeRanks(score) {
const sortedScore = sortDesc([...score]);
const hashmap = buildHashmap(sortedScore);
return getRelativeRanks(score, hashmap);
}
================================================
FILE: coding_interviews/leetcode/easy/relative-sort-array/relative-sort-array.js
================================================
// https://leetcode.com/problems/relative-sort-array
const relativeSortArray = (arr1, arr2) => {
const mapper1 = {};
const mapper2 = {};
arr2.forEach((num) => (mapper2[num] = true));
arr1.forEach((num) => {
if (mapper1[num]) mapper1[num].push(num);
else if (mapper2[num]) mapper1[num] = [num];
else if (mapper1['other']) mapper1['other'].push(num);
else mapper1['other'] = [num];
});
const sortedArr = [];
arr2.forEach((num) => {
sortedArr.push(...mapper1[num]);
});
if (mapper1['other'])
sortedArr.push(...mapper1['other'].sort((a, b) => a - b));
return sortedArr;
};
================================================
FILE: coding_interviews/leetcode/easy/remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.js
================================================
function deleteDuplicates(head) {
if (!head || !head.next) {
return head;
}
let current = head;
let next = current.next;
while (next) {
if (current.val === next.val) {
next = next.next;
current.next = next;
} else {
current = next;
next = next.next;
}
}
return head;
}
================================================
FILE: coding_interviews/leetcode/easy/remove-linked-list-elements/remove-linked-list-elements.js
================================================
function removeElements(head, val) {
if (!head) return head;
while (head && head.val === val) {
head = head.next;
}
if (!head) return head;
let previous = head;
let current = head.next;
while (current) {
if (current.val === val) {
previous.next = current.next;
current = previous.next;
} else {
previous = previous.next;
current = current.next;
}
}
return head;
}
================================================
FILE: coding_interviews/leetcode/easy/remove-outermost-parentheses/remove-outermost-parentheses.js
================================================
export function removeOuterParentheses(string) {
const stack = [];
const result = [];
for (let i = 0; i < string.length; i++) {
const char = string[i];
if (char === '(') {
if (stack.length) {
result.push(char);
}
stack.push(char);
} else {
if (stack.length > 1) {
result.push(char);
}
stack.pop();
}
}
return result.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/remove-outermost-parentheses/tests/remove-outermost-parentheses.test.js
================================================
import { describe, expect, it } from 'vitest';
import { removeOuterParentheses } from '../remove-outermost-parentheses';
describe('removeOuterParentheses', () => {
it('', () => {
expect(removeOuterParentheses('(()())(())')).toEqual('()()()');
});
it('', () => {
expect(removeOuterParentheses('(()())(())(()(()))')).toEqual(
'()()()()(())'
);
});
it('', () => {
expect(removeOuterParentheses('()()')).toEqual('');
});
});
================================================
FILE: coding_interviews/leetcode/easy/remove-palindromic-subsequences/remove-palindromic-subsequences.js
================================================
function isPalindrome(s) {
return s === s.split('').reverse().join('');
}
function removePalindromeSub(s) {
return isPalindrome(s) ? 1 : 2;
}
================================================
FILE: coding_interviews/leetcode/easy/remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.js
================================================
function removeTrailingZeros(num) {
let result = '';
let trailing = true;
for (let index = num.length - 1; index >= 0; index--) {
if (num[index] === '0' && trailing) {
continue;
} else {
trailing = false;
result = num[index] + result;
}
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/remove_duplicates/remove_duplicates.py
================================================
# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string
def remove_duplicates(S):
if len(S) <= 1: return S
start, end = 0, 1
while end < len(S):
if S[start] != S[end]:
start = end
end = start + 1
elif S[start] == S[end] and end + 1 == len(S):
S = S[0:start]
elif S[start] == S[end]:
S = S[0:start] + S[end+1:]
start, end = 0, 1
return S
def remove_duplicates(S):
stack = []
for char in S:
if len(stack) and stack[-1] == char:
stack.pop()
else:
stack.append(char)
return ''.join(stack)
================================================
FILE: coding_interviews/leetcode/easy/remove_duplicates.py
================================================
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
'''
- Examples:
[1, 1, 2] # => 2
[] # => 0
[1, 1, 1] # => 1
[1, 2, 3, 3, 4, 5] # => 5
'''
def remove_duplicates(nums):
if not nums:
return 0
total_result = 1
num = nums[0]
for index in range(1, len(nums)):
if nums[index] != num:
nums[total_result] = nums[index]
total_result += 1
num = nums[index]
return total_result
list1 = [1, 1, 2]
list2 = []
list3 = [1, 1, 1]
list4 = [1, 2, 3, 3, 4, 5]
print remove_duplicates(list1)
print remove_duplicates(list2)
print remove_duplicates(list3)
print remove_duplicates(list4)
print list1
print list2
print list3
print list4
================================================
FILE: coding_interviews/leetcode/easy/remove_duplicates_from_list.py
================================================
# https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
class ListNode(object):
def __init__(self, value):
self.val = value
self.next = None
def remove_duplicates(head):
if head is None:
return
current_node = head
while current_node and current_node.next:
if current_node.val == current_node.next.val:
current_node.next = current_node.next.next
else:
current_node = current_node.next
return head
# 1 -> 1 -> 2
print('1 -> 1 -> 2')
head = ListNode(1)
head.next = ListNode(1)
head.next.next = ListNode(2)
current_node = remove_duplicates(head)
while current_node:
print(current_node.val)
current_node = current_node.next
# 1 -> 1 -> 2 -> 3 -> 3
print('\n1 -> 1 -> 2 -> 3 -> 3')
head = ListNode(1)
head.next = ListNode(1)
head.next.next = ListNode(2)
head.next.next.next = ListNode(3)
head.next.next.next.next = ListNode(3)
current_node = remove_duplicates(head)
while current_node:
print(current_node.val)
current_node = current_node.next
================================================
FILE: coding_interviews/leetcode/easy/remove_element.py
================================================
# https://leetcode.com/problems/remove-element/description/
'''
nums = [3, 2, 2, 3], val = 3 # => 2
nums = [3, 2, 2, 3], val = 2 # => 2
nums = [1, 2, 2, 4], val = 3 # => 4
nums = [], val = 3 # => 0
'''
def remove_element(nums, val):
while val in nums:
nums.remove(val)
return len(nums)
================================================
FILE: coding_interviews/leetcode/easy/replace_digits/replace_digits.py
================================================
# https://leetcode.com/problems/replace-all-digits-with-characters
def replace_digits(s):
replaced_string = []
for index in range(len(s)):
if index % 2 == 0:
replaced_string.append(s[index])
else:
replaced_string.append(shift(s[index-1], s[index]))
return ''.join(replaced_string)
def shift(char, digit):
return chr(ord(char) + int(digit))
================================================
FILE: coding_interviews/leetcode/easy/replace_elements/replace_elements.py
================================================
# https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side
def replace_elements(arr):
index, max_num = len(arr) - 1, -1
for number in reversed(arr):
arr[index] = max_num
max_num = max(number, max_num)
index -= 1
return arr
================================================
FILE: coding_interviews/leetcode/easy/reshape-the-matrix/reshape-the-matrix.js
================================================
function matrixReshape(mat, r, c) {
if (mat.length * mat[0].length !== r * c) {
return mat;
}
let reshapedMatrix = [];
let reshapedMatrixRow = [];
let index = 0;
for (let row = 0; row < mat.length; row++) {
for (let col = 0; col < mat[row].length; col++) {
const num = mat[row][col];
if (index < c) {
reshapedMatrixRow.push(num);
} else {
reshapedMatrix.push(reshapedMatrixRow);
reshapedMatrixRow = [num];
index = 0;
}
index++;
}
}
reshapedMatrix.push(reshapedMatrixRow);
return reshapedMatrix;
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-linked-list/reverse-linked-list.js
================================================
function reverseList(head) {
if (!head) {
return head;
}
let firstNode = head;
let secondNode = head.next;
let auxiliaryNode = null;
let previousNode = null;
while (secondNode) {
auxiliaryNode = secondNode.next;
secondNode.next = firstNode;
firstNode.next = previousNode;
previousNode = firstNode;
firstNode = secondNode;
secondNode = auxiliaryNode;
}
return firstNode;
}
function reverseListSimpler(head) {
let previous = null;
let current = head;
let next;
while (current) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-only-letters/reverse-only-letters.js
================================================
function isEnglishLetter(char) {
return (
(char.charCodeAt() >= 65 && char.charCodeAt() <= 90) ||
(char.charCodeAt() >= 97 && char.charCodeAt() <= 122)
);
}
function reverseOnlyLetters(s) {
const englishLetter = [];
for (let char of s) {
if (isEnglishLetter(char)) englishLetter.push(char);
}
let index = englishLetter.length - 1;
let output = s.split('');
for (let i = 0; i < s.length; i++) {
if (isEnglishLetter(s[i])) {
output[i] = englishLetter[index];
index--;
}
}
return output.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-prefix-of-word/reverse-prefix-of-word.js
================================================
function reverse(charsList) {
const reversedCharsList = [];
for (let i = charsList.length - 1; i >= 0; i--) {
reversedCharsList.push(charsList[i]);
}
return reversedCharsList;
}
export function reversePrefix(word, char) {
let charsList = [];
let foundFirstOccurrence = false;
for (let i = 0; i < word.length; i++) {
const wordChar = word[i];
charsList.push(wordChar);
if (wordChar === char && !foundFirstOccurrence) {
foundFirstOccurrence = true;
charsList = reverse(charsList);
}
}
return charsList.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-prefix-of-word/tests/reverse-prefix-of-word.test.js
================================================
import { describe, it, expect } from 'vitest';
import { reversePrefix } from '../reverse-prefix-of-word';
describe('reversePrefix', () => {
it('reverses the prefix', () => {
expect(reversePrefix('abcdefd', 'd')).toEqual('dcbaefd');
});
it('reverses the prefix', () => {
expect(reversePrefix('xyxzxe', 'z')).toEqual('zxyxxe');
});
it('reverses the prefix', () => {
expect(reversePrefix('abcd', 'z')).toEqual('abcd');
});
});
================================================
FILE: coding_interviews/leetcode/easy/reverse-string/reverse-string-in-place.js
================================================
function reverseString(s) {
let pointer1 = 0;
let pointer2 = s.length - 1;
let auxiliaryChar;
while (pointer1 < pointer2) {
auxiliaryChar = s[pointer1];
s[pointer1] = s[pointer2];
s[pointer2] = auxiliaryChar;
pointer1++;
pointer2--;
}
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-string/reverse-string.js
================================================
function reverseString(s) {
let reversedString = [];
for (let index = s.length - 1; index >= 0; index--) {
reversedString.push(s[index]);
}
return reversedString;
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-vowels-of-a-string/reverse-vowels-of-a-string.js
================================================
function reverseVowels(s) {
const allVowels = [];
const vowels = 'aeiouAEIOU';
for (let char of s) {
if (vowels.includes(char)) allVowels.push(char);
}
const reversedVowels = [];
for (
let index = 0, vowelIndex = allVowels.length - 1;
index < s.length;
index++
) {
if (vowels.includes(s[index])) {
reversedVowels.push(allVowels[vowelIndex]);
vowelIndex--;
} else {
reversedVowels.push(s[index]);
}
}
return reversedVowels.join('');
}
================================================
FILE: coding_interviews/leetcode/easy/reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.js
================================================
function reverseWords(s) {
let reversedString = [];
let splittedString = s.split(' ');
for (let word of splittedString) {
let reversedWord = [];
for (let index = word.length - 1; index >= 0; index--) {
reversedWord.push(word[index]);
}
reversedString.push(reversedWord.join(''));
}
return reversedString.join(' ');
}
================================================
FILE: coding_interviews/leetcode/easy/reverse_integer.py
================================================
# https://leetcode.com/problems/reverse-integer/
def reverse(x):
number_list = []
if x < 0:
negative = True
x *= -1
else:
negative = False
while x > 0:
number_list.append(x % 10)
x /= 10
result_number = 0
for index, n in enumerate(number_list):
result_number += n * pow(10, len(number_list) - 1 - index)
if negative:
result_number *= -1
if (result_number < 2147483648*-1 or result_number > 2147483647):
return 0
return result_number
================================================
FILE: coding_interviews/leetcode/easy/reverse_string.py
================================================
'''
https://leetcode.com/problems/reverse-string/description/
input: "hello"
output: "olleh"
'''
def reverse_string(s):
return s[::-1]
================================================
FILE: coding_interviews/leetcode/easy/reverse_vowels.py
================================================
'''
https://leetcode.com/problems/reverse-vowels-of-a-string/description/
input: "hello"
output: "holle"
input: "leetcode"
output: "leotcede"
'''
def vowel(char):
return char in ['a', 'e', 'i', 'o', 'u']
def reverse_vowels(s):
vowels = [char for char in s if vowel(char)]
index = len(vowels) - 1
result = ''
for char in s:
if vowel(char):
result += vowels[index]
index -= 1
else:
result += char
return result
print(reverse_vowels('hello') == 'holle')
print(reverse_vowels('leetcode') == 'leotcede')
================================================
FILE: coding_interviews/leetcode/easy/reverse_words_string.py
================================================
'''
https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
input: "Let's take LeetCode contest"
output: "s'teL ekat edoCteeL tsetnoc"
'''
def reverse_words(s):
return ' '.join([word[::-1] for word in s.split(' ')])
print(reverse_words("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc")
================================================
FILE: coding_interviews/leetcode/easy/rings-and-rods/rings-and-rods.js
================================================
/*
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.
You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:
The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').
The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').
For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.
Return the number of rods that have all three colors of rings on them.
Input: rings = "B0B6G0R6R0R6G9"
Output: 1
Input: rings = "B0R0G0R9R0B0G0"
Output: 1
*/
export function countPoints(rings = '') {
const rods = {
0: new Set(),
1: new Set(),
2: new Set(),
3: new Set(),
4: new Set(),
5: new Set(),
6: new Set(),
7: new Set(),
8: new Set(),
9: new Set(),
};
for (let i = 0; i < rings.length - 1; i += 2) {
const color = rings[i];
const position = rings[i + 1];
rods[position].add(color);
}
return Object.values(rods).reduce(
(count, colors) => (colors.size === 3 ? count + 1 : count),
0
);
}
================================================
FILE: coding_interviews/leetcode/easy/rings-and-rods/tests/rings-and-rods.test.js
================================================
import { describe, expect, it } from 'vitest';
import { countPoints } from '../rings-and-rods';
describe('countPoints', () => {
it('', () => {
expect(countPoints('B0B6G0R6R0R6G9')).toEqual(1);
});
it('', () => {
expect(countPoints('B0R0G0R9R0B0G0')).toEqual(1);
});
});
================================================
FILE: coding_interviews/leetcode/easy/root-equals-sum-of-children/index.js
================================================
function checkTree(root) {
return root.val === root.left.val + root.right.val;
}
================================================
FILE: coding_interviews/leetcode/easy/row-with-maximum-ones/row-with-maximum-ones.js
================================================
// https://leetcode.com/problems/row-with-maximum-ones
function rowAndMaximumOnes(mat) {
let rowIndex;
let maxCountOfOnes = -Infinity;
for (let row = 0; row < mat.length; row++) {
let countOfOnes = 0;
for (let num of mat[row]) {
if (num === 1) {
countOfOnes++;
}
}
if (countOfOnes > maxCountOfOnes) {
maxCountOfOnes = countOfOnes;
rowIndex = row;
}
}
return [rowIndex, maxCountOfOnes];
}
================================================
FILE: coding_interviews/leetcode/easy/running_array_sum/running_array_sum.py
================================================
def running_sum(nums):
sum = 0
result = []
for num in nums:
sum += num
result.append(sum)
return result
================================================
FILE: coding_interviews/leetcode/easy/same-tree/same-tree.js
================================================
function isSameTree(p, q) {
if (!p && !q) return true;
if ((!p && q) || (!q && p)) return false;
return (
p.val === q.val &&
isSameTree(p.left, q.left) &&
isSameTree(p.right, q.right)
);
}
================================================
FILE: coding_interviews/leetcode/easy/same_tree.py
================================================
# https://leetcode.com/problems/same-tree/description/
def is_same_tree(p, q):
if (p and not q) or (not p and q):
return False
if not p and not q:
return True
return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
def is_same_tree(p, q):
if p and q:
return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
return p is q
================================================
FILE: coding_interviews/leetcode/easy/search-in-a-binary-search-tree/search-in-a-binary-search-tree.js
================================================
function searchBST(root, val) {
if (!root) {
return null;
}
if (root.val === val) {
return root;
}
return searchBST(root.left, val) || searchBST(root.right, val);
}
================================================
FILE: coding_interviews/leetcode/easy/search-insert-position/search-insert-position-new.js
================================================
function getMiddle(start, end) {
return Math.floor((start + end) / 2);
}
function searchInsert(nums, target) {
let start = 0;
let end = nums.length - 1;
let middle = getMiddle(start, end);
while (start <= end) {
if (target < nums[middle]) {
end = middle - 1;
middle = getMiddle(start, end);
} else if (target > nums[middle]) {
start = middle + 1;
middle = getMiddle(start, end);
} else {
return middle;
}
}
return middle + 1;
}
================================================
FILE: coding_interviews/leetcode/easy/search-insert-position/search-insert-position.js
================================================
// https://leetcode.com/problems/search-insert-position
const searchInsert = (nums, target) => {
let start = 0;
let end = nums.length - 1;
while (start <= end) {
middle = Math.floor((start + end) / 2);
if (nums[middle] === target) return middle;
if (target > nums[middle]) start = middle + 1;
if (target < nums[middle]) end = middle - 1;
}
return start;
};
const print = (nums, target) => console.log(searchInsert(nums, target));
print([1, 3, 5, 6], 5);
print([1, 3, 5, 6], 2);
print([1, 3, 5, 6], 7);
print([1, 3, 5, 6], 0);
print([1], 0);
================================================
FILE: coding_interviews/leetcode/easy/search_in_a_binary_search_tree/search_in_a_binary_search_tree.py
================================================
# https://leetcode.com/problems/search-in-a-binary-search-tree
def searchBST(root, val):
if root and val < root.val:
return searchBST(root.left, val)
if root and val > root.val:
return searchBST(root.right, val)
return root
================================================
FILE: coding_interviews/leetcode/easy/second-largest-digit-in-a-string/second-largest-digit-in-a-string.js
================================================
// https://leetcode.com/problems/second-largest-digit-in-a-string
function secondHighest(s) {
let highest = -1;
let secHighest = -1;
for (let char of s) {
let numChar = Number(char);
let isInt = Number.isInteger(numChar);
if (isInt && numChar > highest) {
secHighest = highest;
highest = numChar;
} else if (isInt && numChar !== highest && numChar > secHighest) {
secHighest = numChar;
}
}
return highest === secHighest ? -1 : secHighest;
}
================================================
FILE: coding_interviews/leetcode/easy/self_dividing_numbers.py
================================================
'''
https://leetcode.com/problems/self-dividing-numbers/description/
Input: left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
'''
def self_dividing_numbers(left, right):
output = [number for number in range(left, right + 1) if dividing(number, number)]
return output
def dividing(number, original):
if number == 0: return True
if number % 10 == 0: return False
return dividing(number / 10, original) and original % (number % 10) == 0
print(self_dividing_numbers(1, 22) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22])
================================================
FILE: coding_interviews/leetcode/easy/semi-ordered-permutation/semi-ordered-permutation.js
================================================
// https://leetcode.com/problems/semi-ordered-permutation
function semiOrderedPermutation(nums) {
let N = nums.length;
let indexFirst;
let indexLast;
for (let index = 0; index < N; index++) {
if (nums[index] === 1) indexFirst = index;
if (nums[index] === N) indexLast = index;
}
let swaps = indexFirst;
if (indexFirst > indexLast) swaps += N - indexLast - 2;
else swaps += N - indexLast - 1;
return swaps;
}
================================================
FILE: coding_interviews/leetcode/easy/separate-the-digits-in-an-array/separate-the-digits-in-an-array.js
================================================
function separateDigits(nums) {
const answer = [];
for (let num of nums) {
const numString = num.toString();
for (let charNum of numString) {
answer.push(Number(charNum));
}
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/easy/shortest_to_char/shortest_to_char.py
================================================
# https://leetcode.com/problems/shortest-distance-to-a-character
def shortest_to_char(s, c):
all_c_indexes = []
for index, char in enumerate(s):
if char == c:
all_c_indexes.append(index)
answer = []
for index, char in enumerate(s):
if char == c:
answer.append(0)
else:
answer_index = float('Inf')
for c_index in all_c_indexes:
answer_index = min(answer_index, abs(c_index - index))
answer.append(answer_index)
return answer
def shortest_to_char(s, c):
previous = float('-Inf')
answer = []
for index, char in enumerate(s):
if char == c:
previous = index
answer.append(index - previous)
previous = float('Inf')
for index in range(len(s) - 1, -1, -1):
if s[index] == c:
previous = index
answer[index] = min(answer[index], previous - index)
return answer
================================================
FILE: coding_interviews/leetcode/easy/shuffle_string/shuffle_string.py
================================================
# shuffle string
# https://leetcode.com/problems/shuffle-string
def restore_string(s, indices):
index_to_char_mapper = {}
for index in range(len(s)):
index_to_char_mapper[indices[index]] = s[index]
return ''.join([index_to_char_mapper[index] for index in range(len(s))])
================================================
FILE: coding_interviews/leetcode/easy/shuffle_the_array/shuffle_the_array.py
================================================
def shuffle(nums, n):
first_half = nums[:n]
last_half = nums[n:]
final_list = []
for index in range(len(first_half)):
final_list.append(first_half[index])
final_list.append(last_half[index])
return final_list
================================================
FILE: coding_interviews/leetcode/easy/sign_of_the_product_of_an_array/sign_of_the_product_of_an_array.py
================================================
# https://leetcode.com/problems/sign-of-the-product-of-an-array
def array_sign(nums):
product = 1
for num in nums:
if num == 0: return 0
product *= num
if product > 0:
return 1
if product < 0:
return -1
================================================
FILE: coding_interviews/leetcode/easy/single-number/single-number.js
================================================
function singleNumber(nums) {
let hashmap = {};
for (let num of nums) {
if (hashmap[num]) {
hashmap[num]++;
} else {
hashmap[num] = 1;
}
}
for (let num of nums) {
if (hashmap[num] === 1) {
return num;
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/single_number/single_number.py
================================================
# https://leetcode.com/problems/single-number
def single_number(nums):
counter = {}
for num in nums:
if num in counter:
counter[num] += 1
else:
counter[num] = 1
for num in nums:
if counter[num] == 1: return num
================================================
FILE: coding_interviews/leetcode/easy/slowest-key/slowest-key.js
================================================
function isLexicographicallyLarger(keysPressed, keyPressedIndex, index) {
return keysPressed[index] > keysPressed[keyPressedIndex];
}
function slowestKey(releaseTimes, keysPressed) {
let longestDuration = releaseTimes[0];
let previousRelease = releaseTimes[0];
let keyPressedIndex = 0;
for (let index = 1; index < releaseTimes.length; index++) {
let currentRelease = releaseTimes[index];
let currentDuration = currentRelease - previousRelease;
if (currentDuration > longestDuration) {
longestDuration = currentDuration;
keyPressedIndex = index;
}
if (
currentDuration === longestDuration &&
isLexicographicallyLarger(keysPressed, keyPressedIndex, index)
) {
longestDuration = currentDuration;
keyPressedIndex = index;
}
previousRelease = currentRelease;
}
return keysPressed[keyPressedIndex];
}
function slowestKey(releaseTimes, keysPressed) {
let longestDuration = releaseTimes[0];
let previousRelease = releaseTimes[0];
let keyPressedIndex = 0;
for (let index = 1; index < releaseTimes.length; index++) {
let currentRelease = releaseTimes[index];
let currentDuration = currentRelease - previousRelease;
if (
currentDuration > longestDuration ||
(currentDuration === longestDuration &&
isLexicographicallyLarger(keysPressed, keyPressedIndex, index))
) {
longestDuration = currentDuration;
keyPressedIndex = index;
}
previousRelease = currentRelease;
}
return keysPressed[keyPressedIndex];
}
================================================
FILE: coding_interviews/leetcode/easy/smallest-even-multiple/smallest-even-multiple.js
================================================
function smallestEvenMultiple(n) {
return n % 2 === 0 ? n : n * 2;
}
================================================
FILE: coding_interviews/leetcode/easy/smallest-index-with-equal-value/smallest-index-with-equal-value.js
================================================
function smallestEqual(nums) {
for (let [index, num] of nums.entries()) {
if (index % 10 === num) {
return index;
}
}
return -1;
}
================================================
FILE: coding_interviews/leetcode/easy/smallest-range-i/optimized-smallest-range-i.js
================================================
// https://leetcode.com/problems/smallest-range-i
function minMax(nums) {
let min = Infinity;
let max = -Infinity;
for (let num of nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
return [min, max];
}
function smallestRangeI(nums, k) {
let [min, max] = minMax(nums);
return Math.max(0, max - k - (min + k));
}
================================================
FILE: coding_interviews/leetcode/easy/smallest-range-i/smallest-range-i.js
================================================
// https://leetcode.com/problems/smallest-range-i
function smallestRangeI(nums, k) {
let smaller = Infinity;
let bigger = -Infinity;
for (let num of nums) {
smaller = Math.min(smaller, num);
bigger = Math.max(bigger, num);
}
let middle = Math.floor((bigger + smaller) / 2);
let min = Infinity;
let max = -Infinity;
if (k > bigger - middle) {
max = middle;
} else {
max = bigger - k;
}
if (k > middle - smaller) {
min = middle;
} else {
min = smaller + k;
}
return max - min;
}
================================================
FILE: coding_interviews/leetcode/easy/smallest-range-i/smallest-range-iI.js
================================================
// https://leetcode.com/problems/smallest-range-i
function smallestRangeI(nums, k) {
let min = Math.min(...nums);
let max = Math.max(...nums);
return Math.max(0, max - k - (min + k));
}
================================================
FILE: coding_interviews/leetcode/easy/smallest_numbers/smallest_numbers.py
================================================
# https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number
'''
nums = [8,1,2,2,3]
[4,0,1,1,3]
nums = [6,5,4,8]
[2,1,0,3]
'''
'''
O(Nˆ2): Runtime / O(N): Space
'''
def smaller_numbers_than_current(nums):
smaller_numbers_counters = []
for num in nums:
counter = 0
for compared_num in nums:
if compared_num < num:
counter += 1
smaller_numbers_counters.append(counter)
return smaller_numbers_counters
'''
O(NlogN): Runtime / O(N): Space
'''
def smaller_numbers_than_current_2(nums):
smaller_numbers_counters = {}
for index, num in enumerate(sorted(nums)):
if num not in smaller_numbers_counters:
smaller_numbers_counters[num] = index
return [smaller_numbers_counters[num] for num in nums]
data_tests = [
([8, 1, 2, 2, 3], [4, 0, 1, 1, 3]),
([6, 5, 4, 8], [2, 1, 0, 3])
]
for numbers, expected in data_tests:
result = smaller_numbers_than_current(numbers)
print(result, result == expected)
result = smaller_numbers_than_current_2(numbers)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/sort-array-by-increasing-frequency/sort-array-by-increasing-frequency.js
================================================
function buildCounter(nums) {
let counter = new Map();
for (let num of nums) {
if (counter.has(num)) counter.set(num, counter.get(num) + 1);
else counter.set(num, 1);
}
return counter;
}
function toPairs(counter) {
const pairs = [];
for (let [key, value] of counter.entries()) {
pairs.push([key, value]);
}
return pairs;
}
function byCount(pair1, pair2) {
if (pair1[1] < pair2[1]) return -1;
if (pair1[1] === pair2[1] && pair1[0] >= pair2[0]) return -1;
if (pair1[1] === pair2[1] && pair1[0] < pair2[0]) return 1;
if (pair1[1] > pair2[1]) return 1;
return 0;
}
function buildResult(pairs) {
const result = [];
for (let [num, count] of pairs) {
for (let counter = 1; counter <= count; counter++) {
result.push(num);
}
}
return result;
}
function frequencySort(nums) {
const counter = buildCounter(nums);
const pairs = toPairs(counter);
pairs.sort(byCount);
return buildResult(pairs);
}
================================================
FILE: coding_interviews/leetcode/easy/sort-array-by-parity/sort-array-by-parity-two-loops.js
================================================
// https://leetcode.com/problems/sort-array-by-parity
function sortArrayByParity(nums) {
let output = [];
for (let num of nums) {
if (num % 2 === 0) output.push(num);
}
for (let num of nums) {
if (num % 2 !== 0) output.push(num);
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/sort-array-by-parity/sort-array-by-parity.js
================================================
// https://leetcode.com/problems/sort-array-by-parity
function sortArrayByParity(nums) {
let odd = [];
let even = [];
for (let num of nums) {
if (num % 2 === 0) even.push(num);
else odd.push(num);
}
return [...even, ...odd];
}
================================================
FILE: coding_interviews/leetcode/easy/sort-array-by-parity-ii/sort-array-by-parity-ii.js
================================================
function isEven(num) {
return num % 2 === 0;
}
function separateIntoEvensAndOdds(nums) {
let evens = [];
let odds = [];
for (let num of nums) {
if (isEven(num)) evens.push(num);
else odds.push(num);
}
return [evens, odds];
}
export function sortArrayByParityII(nums) {
let [evens, odds] = separateIntoEvensAndOdds(nums);
let result = [];
for (let index = 0; index < evens.length; index++) {
result.push(evens[index]);
result.push(odds[index]);
}
return result;
}
export function sortArrayByParityIIInPlace(nums) {
for (let index = 0; index < nums.length - 1; index++) {
if (isEven(index) !== isEven(nums[index])) {
for (let index2 = index + 1; index2 < nums.length; index2++) {
if (isEven(index) === isEven(nums[index2])) {
let num = nums[index];
nums[index] = nums[index2];
nums[index2] = num;
break;
}
}
}
}
return nums;
}
================================================
FILE: coding_interviews/leetcode/easy/sort-array-by-parity-ii/tests/sort-array-by-parity-ii.test.js
================================================
import { describe, it, expect } from 'vitest';
import {
sortArrayByParityII,
sortArrayByParityIIInPlace,
} from '../sort-array-by-parity-ii';
describe('sortArrayByParityII', () => {
it('', () => {
expect(sortArrayByParityII([4, 2, 5, 7])).toEqual([4, 5, 2, 7]);
});
it('', () => {
expect(sortArrayByParityII([2, 3])).toEqual([2, 3]);
});
it('', () => {
expect(sortArrayByParityII([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual([
2, 1, 4, 3, 6, 5, 8, 7, 10, 9,
]);
});
it('', () => {
expect(sortArrayByParityII([2, 3, 1, 1, 4, 0, 0, 4, 3, 3])).toEqual([
2, 3, 4, 1, 0, 1, 0, 3, 4, 3,
]);
});
});
describe('sortArrayByParityIIInPlace', () => {
it('', () => {
expect(sortArrayByParityIIInPlace([4, 2, 5, 7])).toEqual([4, 5, 2, 7]);
});
it('', () => {
expect(sortArrayByParityIIInPlace([2, 3])).toEqual([2, 3]);
});
it('', () => {
expect(sortArrayByParityIIInPlace([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual(
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
);
});
it('', () => {
expect(sortArrayByParityIIInPlace([2, 3, 1, 1, 4, 0, 0, 4, 3, 3])).toEqual([
2, 3, 4, 1, 0, 1, 0, 3, 4, 3,
]);
});
});
================================================
FILE: coding_interviews/leetcode/easy/sort-even-and-odd-indices-independently/sort-even-and-odd-indices-independently.js
================================================
function decreasing(a, b) {
return b - a;
}
function increasing(a, b) {
return a - b;
}
function sortEvenOdd(nums) {
let evens = [];
let odds = [];
for (let index = 0; index < nums.length; index++) {
if (index % 2 === 0) evens.push(nums[index]);
else odds.push(nums[index]);
}
evens.sort(increasing);
odds.sort(decreasing);
let result = [];
let biggerLength = evens.length > odds.length ? evens.length : odds.length;
for (let index = 0; index < biggerLength; index++) {
if (index < evens.length) result.push(evens[index]);
if (index < odds.length) result.push(odds[index]);
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/sort-integers-by-the-number-of-1-bits/sort-integers-by-the-number-of-1-bits.js
================================================
function toBinary(num) {
if (num === 0) return { binary: '0', numberOfOneBits: 0 };
let binary = [];
let numberOfOneBits = 0;
let numCopy = num;
while (numCopy > 0) {
const binaryDigit = numCopy % 2;
if (binaryDigit) numberOfOneBits++;
binary.unshift(String(binaryDigit));
numCopy = Math.floor(numCopy / 2);
}
return { num, binary: binary.join(''), numberOfOneBits };
}
function byNumberOfOneBits(binary1, binary2) {
if (binary1.numberOfOneBits < binary2.numberOfOneBits) return -1;
if (binary1.numberOfOneBits > binary2.numberOfOneBits) return 1;
if (
binary1.numberOfOneBits === binary2.numberOfOneBits &&
binary1.num < binary2.num
)
return -1;
return 0;
}
function sortByBits(nums) {
const hashmap = new Map();
const binaries = [];
const result = [];
for (let num of nums) {
const binary = toBinary(num);
hashmap.set(binary.binary, num);
binaries.push(binary);
}
binaries.sort(byNumberOfOneBits);
for (let { binary } of binaries) {
result.push(hashmap.get(binary));
}
return result;
}
================================================
FILE: coding_interviews/leetcode/easy/sort-the-people/sort-the-people.js
================================================
function sortPeople(names, heights) {
const heightToName = new Map();
for (let index = 0; index < names.length; index++) {
const name = names[index];
const height = heights[index];
heightToName.set(height, name);
}
return heights
.sort((height1, height2) => height2 - height1)
.map((height) => heightToName.get(height));
}
================================================
FILE: coding_interviews/leetcode/easy/sort_array_by_parity/sort_array_by_parity.py
================================================
# https://leetcode.com/problems/sort-array-by-parity/submissions/
'''
Given an array A of non-negative integers,
return an array consisting of all the even elements of A,
followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example:
Input: [3,1,2,4]
Output: [2,4,3,1]
'''
def sort_array_by_parity(A):
even_numbers = []
odd_numbers = []
for number in A:
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
return even_numbers + odd_numbers
data_tests = [
([1, 2, 3, 4], [2, 4, 1, 3]),
([3, 1, 2, 4], [2, 4, 3, 1]),
]
for numbers, expected in data_tests:
result = sort_array_by_parity(numbers)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/sort_sentence/sort_sentence.py
================================================
# https://leetcode.com/problems/sorting-the-sentence
def sort_sentence(s):
words = s.split()
index_to_word = {}
for word in words:
index = int(word[-1])
actual_word = word[:len(word) - 1]
index_to_word[index] = actual_word
sentence = []
for index in range(1, len(words) + 1):
sentence.append(index_to_word[index])
return ' '.join(sentence)
================================================
FILE: coding_interviews/leetcode/easy/special-positions-in-a-binary-matrix/special-positions-in-a-binary-matrix-cache.js
================================================
function countOnesInRow(matrix, row) {
let ones = 0;
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] === 1) ones++;
}
return ones;
}
function countOnesInCol(matrix, col) {
let ones = 0;
for (let row = 0; row < matrix.length; row++) {
if (matrix[row][col] === 1) ones++;
}
return ones;
}
function numSpecial(matrix) {
let specialPositions = 0;
let hashmapRow = new Map();
let hashmapCol = new Map();
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
let rowOnes = hashmapRow.has(row)
? hashmapRow.get(row)
: countOnesInRow(matrix, row);
hashmapRow.set(row, rowOnes);
let colOnes = hashmapCol.has(col)
? hashmapCol.get(col)
: countOnesInCol(matrix, col);
hashmapCol.set(col, colOnes);
if (matrix[row][col] === 1 && rowOnes === 1 && colOnes === 1) {
specialPositions++;
}
}
}
return specialPositions;
}
================================================
FILE: coding_interviews/leetcode/easy/special-positions-in-a-binary-matrix/special-positions-in-a-binary-matrix.js
================================================
function countOnesInRow(matrix, row) {
let ones = 0;
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] === 1) ones++;
}
return ones;
}
function countOnesInCol(matrix, col) {
let ones = 0;
for (let row = 0; row < matrix.length; row++) {
if (matrix[row][col] === 1) ones++;
}
return ones;
}
function numSpecial(matrix) {
let specialPositions = 0;
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (
matrix[row][col] === 1 &&
countOnesInRow(matrix, row) === 1 &&
countOnesInCol(matrix, col) === 1
) {
specialPositions++;
}
}
}
return specialPositions;
}
================================================
FILE: coding_interviews/leetcode/easy/split-strings-by-separator/split-strings-by-separator.js
================================================
// https://leetcode.com/problems/split-strings-by-separator
function splitWordsBySeparator(words, separator) {
let output = [];
for (let word of words) {
let start = 0;
for (let index = 0; index < word.length; index++) {
if (word[index] === separator) {
const str = word.slice(start, index);
if (str.length) output.push(str);
start = index + 1;
} else if (index === word.length - 1) {
output.push(word.slice(start, index + 1));
start = index + 1;
}
}
}
return output;
}
================================================
FILE: coding_interviews/leetcode/easy/split-with-minimum-sum/split-with-minimum-sum.js
================================================
function splitNum(num) {
let numsString = num
.toString()
.split('')
.sort((a, b) => a - b);
let firstHalf = [];
let lastHalf = [];
let isFirstHalf = true;
for (let charNum of numsString) {
if (isFirstHalf) firstHalf.push(charNum);
else lastHalf.push(charNum);
isFirstHalf = !isFirstHalf;
}
return Number(firstHalf.join('')) + Number(lastHalf.join(''));
}
================================================
FILE: coding_interviews/leetcode/easy/split_string_in_balanced_strings/split_string_in_balanced_strings.py
================================================
# https://leetcode.com/problems/split-a-string-in-balanced-strings/
def balanced_string_split(s):
els = 0
ares = 0
max = 0
for char in s:
if char == 'L':
els += 1
else:
ares += 1
if els == ares:
max += 1
els = 0
ares = 0
return max
================================================
FILE: coding_interviews/leetcode/easy/squares-of-a-sorted-array/squares-of-a-sorted-array-on.js
================================================
function buildArray(n) {
const list = [];
for (let i = 1; i <= n; i++) {
list.push(0);
}
return list;
}
function sortedSquares(nums) {
let sortedSquaresNumbers = buildArray(0);
let leftIndex = 0;
let rightIndex = nums.length - 1;
let pointer = nums.length - 1;
while (leftIndex <= rightIndex) {
let left = nums[leftIndex];
let right = nums[rightIndex];
if (Math.abs(left) > Math.abs(right)) {
sortedSquaresNumbers[pointer] = Math.pow(left, 2);
leftIndex++;
} else {
sortedSquaresNumbers[pointer] = Math.pow(right, 2);
rightIndex--;
}
pointer--;
}
return sortedSquaresNumbers;
}
================================================
FILE: coding_interviews/leetcode/easy/squares-of-a-sorted-array/squares-of-a-sorted-array.js
================================================
function square(num) {
return num * num;
}
function byIncreasingOrder(num1, num2) {
return num1 - num2;
}
function sortedSquares(nums) {
return nums.map(square).sort(byIncreasingOrder);
}
================================================
FILE: coding_interviews/leetcode/easy/squares_of_a_sorted_array/squares_of_a_sorted_array.py
================================================
# https://leetcode.com/problems/squares-of-a-sorted-array
'''
Given an array of integers A sorted in non-decreasing order,
return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
'''
def squares_of_a_sorted_array(A):
new_array = []
for number in A:
new_array.append(number * number)
return sorted(new_array)
def squares_of_a_sorted_array_in_place(A):
for index in range(len(A)):
A[index] = A[index] * A[index]
return sorted(A)
data_tests = [
([-4, -1, 0, 3, 10], [0, 1, 9, 16, 100]),
([-7, -3, 2, 3, 11], [4, 9, 9, 49, 121])
]
for numbers, expected in data_tests:
result = squares_of_a_sorted_array(numbers)
print(result, result == expected)
result = squares_of_a_sorted_array_in_place(numbers)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/str_str/str_str.py
================================================
'''
https://leetcode.com/problems/implement-strstr
Implement strStr().
Return the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
- Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
- Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
'''
def strStr(haystack, needle):
if needle == '':
return 0
neddle_length = len(needle)
for index in range(len(haystack) - neddle_length + 1):
if haystack[index:index+neddle_length] == needle:
return index
return -1
test_data = [
("hello", "ll", 2),
("aaaaa", "bba", -1),
("other", "", 0),
]
for haystack, needle, expected in test_data:
result = strStr(haystack, needle)
print('result as expected?', result == expected)
================================================
FILE: coding_interviews/leetcode/easy/string-matching-in-an-array/string-matching-in-an-array.js
================================================
function isSubstring(subword, word) {
for (let index = 0; index <= word.length - subword.length; index++) {
if (subword === word.slice(index, index + subword.length)) {
return true;
}
}
return false;
}
function addSubstring(word1, word2, answer) {
if (word1.length <= word2.length) {
isSubstring(word1, word2) && answer.add(word1);
} else {
isSubstring(word2, word1) && answer.add(word2);
}
}
function stringMatching(words) {
let answer = new Set([]);
for (let i = 0; i < words.length - 1; i++) {
for (let j = i + 1; j < words.length; j++) {
let word1 = words[i];
let word2 = words[j];
addSubstring(word1, word2, answer);
}
}
return [...answer];
}
================================================
FILE: coding_interviews/leetcode/easy/subarrays-distinct-element-sum-of-squares-i/subarrays-distinct-element-sum-of-squares-i.js
================================================
// https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i
function sumCounts(nums) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
let set = new Set();
for (let j = i; j < nums.length; j++) {
set.add(nums[j]);
sum += set.size ** 2;
}
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/subdomain_visit_count.py
================================================
'''
https://leetcode.com/problems/subdomain-visit-count/description/
Example 1:
Input: ["9001 discuss.leetcode.com"]
Output: ["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Example 2:
Input: ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output: ["901 mail.com", "50 yahoo.com", "900 google.mail.com", "5 wiki.org","5 org", "1 intel.mail.com", "951 com"]
'''
def update_subdomain_counter(sc, s, c):
if s in sc:
sc[s] += int(c)
else:
sc[s] = int(c)
def subdomain_visits(cpdomains):
subdomain_counter = {}
for cpdomain in cpdomains:
code, subdomain = cpdomain.split(' ')
update_subdomain_counter(subdomain_counter, subdomain, code)
while subdomain.find(".") != -1:
subdomain = subdomain.split('.', 1)[1]
update_subdomain_counter(subdomain_counter, subdomain, code)
return [str(counter) + " " + subdomain for subdomain, counter in subdomain_counter.items()]
print(subdomain_visits(["9001 discuss.leetcode.com"]))
print(subdomain_visits(["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]))
================================================
FILE: coding_interviews/leetcode/easy/substrings-of-size-three-with-distinct-characters/substrings-of-size-three-with-distinct-characters.js
================================================
function isGoodString(string) {
let [char1, char2, char3] = string;
return char1 !== char2 && char1 !== char3 && char2 !== char3;
}
function countGoodSubstrings(string) {
let goodSubstringsCounter = 0;
for (let index = 0; index < string.length - 2; index++) {
const substring = string.slice(index, index + 3);
if (isGoodString(substring)) {
goodSubstringsCounter++;
}
}
return goodSubstringsCounter;
}
================================================
FILE: coding_interviews/leetcode/easy/subtract_product_and_sum/subtract_product_and_sum.py
================================================
# https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer
'''
Given an integer number n, return the difference between the product of its
digits and the sum of its digits.
Input: n = 234
Output: 15
Input: n = 4421
Output: 21
'''
def subtract_product_and_sum(num):
multiplications = 1
additions = 0
for digit in str(num):
multiplications *= int(digit)
additions += int(digit)
return multiplications - additions
data_tests = [
(234, 15),
(4421, 21)
]
for num, expected in data_tests:
result = subtract_product_and_sum(num)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/easy/subtree-of-another-tree/subtree-of-another-tree.js
================================================
function isSame(root, subRoot) {
if (!root && !subRoot) return true;
if (!root || !subRoot || root.val !== subRoot.val) return false;
return isSame(root.left, subRoot.left) && isSame(root.right, subRoot.right);
}
function isSubtree(root, subRoot) {
return root
? isSame(root, subRoot) ||
isSubtree(root.left, subRoot) ||
isSubtree(root.right, subRoot)
: false;
}
================================================
FILE: coding_interviews/leetcode/easy/sum-multiples/sum-multiples.js
================================================
function sumOfMultiples(n) {
let sum = 0;
for (let num = 1; num <= n; num++) {
if (num % 7 === 0 || num % 5 === 0 || num % 3 === 0) {
sum += num;
}
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/sum-of-all-subset-xor-totals/sum-of-all-subset-xor-totals.js
================================================
function getAllSubsets(subset, nums, output, index) {
if (index == nums.length) {
subset.push(output);
return;
}
getAllSubsets(subset, nums, [...output], index + 1);
output.push(nums[index]);
getAllSubsets(subset, nums, [...output], index + 1);
}
function calculateTotalXOR(nums) {
let totalXOR = nums[0];
for (let i = 1; i < nums.length; i++) {
totalXOR = totalXOR ^ nums[i];
}
return totalXOR;
}
function subsetXORSum(nums) {
let total = 0;
let subset = [];
getAllSubsets(subset, nums, [], 0);
for (let list of subset) {
if (list.length) total += calculateTotalXOR(list);
}
return total;
}
console.log(subsetXORSum([1, 2, 3]));
================================================
FILE: coding_interviews/leetcode/easy/sum-of-digits-in-base-k/sum-of-digits-in-base-k.js
================================================
function fromDecimalToK(n, k) {
const baseKN = [];
while (n) {
baseKN.push(n % k);
n = Math.floor(n / k);
}
return baseKN;
}
function sumBase(n, k) {
return fromDecimalToK(n, k).reduce((num, sum) => sum + num, 0);
}
================================================
FILE: coding_interviews/leetcode/easy/sum-of-digits-of-string-after-convert/sum-of-digits-of-string-after-convert.js
================================================
function toNum(char) {
return char.charCodeAt() - 96;
}
function getNumbers(s) {
let numbers = [];
for (let char of s) {
numbers.push(toNum(char));
}
return numbers;
}
function sum(charNums) {
return charNums.reduce(
(sumOfNums, charNum) => sumOfNums + Number(charNum),
0
);
}
function getLucky(s, k) {
let numbers = getNumbers(s);
let digits = numbers.join('').split('');
for (let index = 1; index <= k; index++) {
digits = sum(digits).toString().split('');
}
return Number(digits.join(''));
}
================================================
FILE: coding_interviews/leetcode/easy/sum-of-left-leaves/sum-of-left-leaves.js
================================================
function sumOfLeftLeaves(root, isLeft = false) {
if (!root) return 0;
if (!root.left && !root.right && isLeft) return root.val;
return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
}
================================================
FILE: coding_interviews/leetcode/easy/sum-of-squares-of-special-elements/sum-of-squares-of-special-elements.js
================================================
// https://leetcode.com/problems/sum-of-squares-of-special-elements
function sumOfSquares(nums) {
let sum = 0;
for (let i = 1; i <= nums.length; i++) {
if (nums.length % i === 0) {
sum += nums[i - 1] * nums[i - 1];
}
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/sum-of-values-at-indices-with-k-set-bits/sum-of-values-at-indices-with-k-set-bits.js
================================================
function toBinary(num) {
if (num === 0) return '0';
let binary = [];
while (num > 0) {
binary.unshift(num % 2);
num = Math.floor(num / 2);
}
return binary.join('');
}
function checkSetBits(binary, k) {
let countSetBits = 0;
for (let digit of binary) {
if (digit === '1') countSetBits++;
}
return countSetBits === k;
}
function sumIndicesWithKSetBits(nums, k) {
let sum = 0;
for (let index = 0; index < nums.length; index++) {
let binary = toBinary(index);
console.log(index, binary);
let matchesKSetBits = checkSetBits(binary, k);
if (matchesKSetBits) {
sum += nums[index];
}
}
return sum;
}
================================================
FILE: coding_interviews/leetcode/easy/sum_leaf_binary_numbers/sum_leaf_binary_numbers.py
================================================
# https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers
total_binary_sum = 0
def sum_root_to_leaf(root):
if root is None: return
helper(root, str(root.val))
return total_binary_sum
def helper(node, path):
if node.left:
helper(node.left, path + str(node.left.val))
if node.right:
helper(node.right, path + str(node.right.val))
if node.right is None and node.left is None:
total_binary_sum += int(path, 2)
================================================
FILE: coding_interviews/leetcode/easy/sum_of_all_odd_length_subarrays/sum_of_all_odd_length_subarrays.py
================================================
# https://leetcode.com/problems/sum-of-all-odd-length-subarrays
'''
Time complexity: O(O*A*S) or O(N^3) to simplify, where O = number of odd numbers, A = length of arr, and S = sum of the subarrays
Space complexity: O(1)
'''
def sum_odd_length_subarrays(arr):
odd, sum_of_subarrays = 1, 0
while (odd <= len(arr)):
for index in range(0, len(arr) - odd + 1):
sum_of_subarrays += sum(arr[index:index+odd])
odd += 2
return sum_of_subarrays
'''
Time complexity: O(N)
Space complexity: O(1)
'''
def sum_odd_length_subarrays_optimized(A):
sum_of_subarrays, length_of_A = 0, len(A)
for index, num in enumerate(A):
sum_of_subarrays += ((index + 1) * (length_of_A - index) + 1) // 2 * num
return sum_odd_length_subarrays
================================================
FILE: coding_interviews/leetcode/easy/sum_of_unique_elements/sum_of_unique_elements.py
================================================
# https://leetcode.com/problems/sum-of-unique-elements
def sum_of_unique(nums):
mapper = {}
for num in nums:
if num in mapper:
mapper[num] += 1
else:
mapper[num] = 1
sum_of_unique_nums = 0
for key in mapper:
if mapper[key] == 1:
sum_of_unique_nums += key
return sum_of_unique_nums
================================================
FILE: coding_interviews/leetcode/easy/sum_zero/sum_zero.py
================================================
def sum_zero(n):
zero_sum_array = []
counter = 1
if n % 2 != 0:
zero_sum_array.append(0)
n -= 1
while n:
zero_sum_array.append(counter)
zero_sum_array.append(-counter)
counter += 1
n -= 2
return zero_sum_array
================================================
FILE: coding_interviews/leetcode/easy/symmetric-tree/symmetric-tree.js
================================================
function symmetricNodes(node1, node2) {
if ((!node1 && node2) || (node1 && !node2)) {
return false;
}
if (!node1 && !node2) {
return true;
}
return (
node1.val === node2.val &&
symmetricNodes(node1.left, node2.right) &&
symmetricNodes(node1.right, node2.left)
);
}
function isSymmetric(root) {
if (!root) {
return true;
}
return symmetricNodes(root.left, root.right);
}
================================================
FILE: coding_interviews/leetcode/easy/take-gifts-from-the-richest-pile/take-gifts-from-the-richest-pile.js
================================================
function pickGifts(gifts, k) {
while (k--) {
let maxIndex = -Infinity;
let max = -Infinity;
for (let index = 0; index < gifts.length; index++) {
if (gifts[index] > max) {
maxIndex = index;
max = gifts[index];
}
}
gifts[maxIndex] = Math.floor(Math.sqrt(gifts[maxIndex]));
}
return gifts.reduce((sum, gift) => sum + gift, 0);
}
================================================
FILE: coding_interviews/leetcode/easy/three-consecutive-odds/three-consecutive-odds.js
================================================
function threeConsecutiveOdds(nums) {
let counter = 0;
for (let num of nums) {
if (num % 2 === 0) counter = 0;
else counter++;
if (counter >= 3) return true;
}
return false;
}
================================================
FILE: coding_interviews/leetcode/easy/time-needed-to-buy-tickets/time-needed-to-buy-tickets.js
================================================
function timeRequiredToBuy(tickets, k) {
let count = 0;
let pointer = 0;
while (tickets[k]) {
if (tickets[pointer]) {
tickets[pointer]--;
count++;
}
pointer = (pointer + 1) % tickets.length;
}
return count;
}
================================================
FILE: coding_interviews/leetcode/easy/to_lower_case/to_lower_case.py
================================================
# https://leetcode.com/problems/to-lower-case/
'''
Implement function ToLowerCase() that has a string parameter str,
and returns the same string in lowercase.
Example 1:
Input: "Hello"
Output: "hello"
Example 2:
Input: "here"
Output: "here"
Example 3:
Input: "LOVELY"
Output: "lovely"
'''
def lower_case_char(char):
if ord(char) >= 65 and ord(char) <= 90:
return chr(ord(char) + 32)
return char
def lower_case(str):
list_of_chars = []
for char in str:
list_of_chars.append(lower_case_char(char))
return ''.join(list_of_chars)
data_tests = [
('Hello', 'hello'),
('here', 'here'),
('LOVELY', 'lovely'),
('al&phaBET', 'al&phabet')
]
for string, expected in data_tests:
result = lower_case(string)
print(result, expected == result)
================================================
FILE: coding_interviews/leetcode/easy/toeplitz-matrix/toeplitz-matrix.js
================================================
function isDiagonalToeplitz(matrix, value, row, col) {
if (row >= matrix.length || col >= matrix[row].length) return true;
if (value !== matrix[row][col]) return false;
return isDiagonalToeplitz(matrix, matrix[row][col], row + 1, col + 1);
}
function isToeplitzMatrix(matrix) {
for (let row = 0; row < matrix.length - 1; row++) {
for (let col = 0; col < matrix[row].length - 1; col++) {
if (!isDiagonalToeplitz(matrix, matrix[row][col], row + 1, col + 1))
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/transpose-matrix/transpose-matrix.js
================================================
function transpose(matrix) {
let newMatrix = [];
for (let col = 0; col < matrix[0].length; col++) {
let newRow = [];
for (let row = 0; row < matrix.length; row++) {
newRow.push(matrix[row][col]);
}
newMatrix.push(newRow);
}
return newMatrix;
}
================================================
FILE: coding_interviews/leetcode/easy/truncate_sentence/truncate_sentence.py
================================================
# https://leetcode.com/problems/truncate-sentence
def truncate_sentence(s, k):
start_index, end_index, words = 0, 0, []
for index, char in enumerate(s):
end_index = index
if char == ' ':
words.append(s[start_index:end_index])
start_index = index + 1
words.append(s[start_index:])
truncated_words = []
for word in words[:k]:
truncated_words.append(word)
return ' '.join(truncated_words)
def truncate_sentence(s, k):
start_index, end_index, words = 0, 0, []
for index, char in enumerate(s):
end_index = index
if char == ' ':
words.append(s[start_index:end_index])
start_index = index + 1
words.append(s[start_index:])
return ' '.join(words[:k])
def truncate_sentence(s, k):
return ' '.join(s.split(' ')[0:k])
================================================
FILE: coding_interviews/leetcode/easy/two-furthest-houses-with-different-colors/two-furthest-houses-with-different-colors.js
================================================
function maxDistance(colors) {
let startPointer = 0;
let endPointer = colors.length - 1;
let maximumDistance = -Infinity;
while (endPointer > startPointer) {
if (colors[startPointer] !== colors[endPointer]) {
maximumDistance = endPointer - startPointer;
break;
}
endPointer--;
}
endPointer = colors.length - 1;
while (startPointer < endPointer) {
if (
colors[startPointer] !== colors[endPointer] &&
endPointer - startPointer > maximumDistance
) {
maximumDistance = endPointer - startPointer;
break;
}
startPointer++;
}
return maximumDistance;
}
================================================
FILE: coding_interviews/leetcode/easy/two-out-of-three/two-out-of-three.js
================================================
function buildHashmap(nums) {
let hashmap = new Map();
for (let num of nums) {
hashmap.set(num, true);
}
return hashmap;
}
function checkAndAddNumbers(result, hashmap1, hashmap2, hashmap3) {
hashmap1.forEach((_, num) => {
if (hashmap2.has(num) || hashmap3.has(num)) {
result.add(num);
}
});
}
function twoOutOfThree(nums1, nums2, nums3) {
let hashmap1 = buildHashmap(nums1);
let hashmap2 = buildHashmap(nums2);
let hashmap3 = buildHashmap(nums3);
let result = new Set();
checkAndAddNumbers(result, hashmap1, hashmap2, hashmap3);
checkAndAddNumbers(result, hashmap2, hashmap1, hashmap3);
checkAndAddNumbers(result, hashmap3, hashmap2, hashmap1);
return [...result];
}
================================================
FILE: coding_interviews/leetcode/easy/two-sum/two-sum.js
================================================
function twoSum(nums, target) {
let numbersMap = {};
for (let [index, num] of nums.entries()) {
numbersMap[num] = index;
}
for (let [index, num] of nums.entries()) {
let remainder = target - num;
let remainderIndex = numbersMap[remainder];
if (remainderIndex && index !== remainderIndex) {
return [index, remainderIndex];
}
}
}
================================================
FILE: coding_interviews/leetcode/easy/two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.js
================================================
function dfs(node, hashmap, values) {
if (!node) {
return node;
}
hashmap[node.val] = true;
values.push(node.val);
dfs(node.left, hashmap, values);
dfs(node.right, hashmap, values);
}
function findTarget(root, k) {
let hashmap = {};
let values = [];
dfs(root, hashmap, values);
for (let value of values) {
if (hashmap[k - value] && k - value !== value) {
return true;
}
}
return false;
}
// second try with better memory usage
function dfs2(node, target, hashmap) {
if (!node) {
return false;
}
if (hashmap[target - node.val]) {
return true;
}
hashmap[node.val] = true;
return dfs2(node.left, target, hashmap) || dfs2(node.right, target, hashmap);
}
function findTarget2(root, k) {
return dfs2(root, k, {});
}
================================================
FILE: coding_interviews/leetcode/easy/two_sum.py
================================================
# https://leetcode.com/problems/two-sum/description/
def two_sum(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
================================================
FILE: coding_interviews/leetcode/easy/uncommon-words-from-two-sentences/uncommon-words-from-two-sentences.js
================================================
function buildCounter(sentence) {
let counter = new Map();
for (let word of sentence) {
if (counter.has(word)) counter.set(word, counter.get(word) + 1);
else counter.set(word, 1);
}
return counter;
}
function getOnceWords(counter) {
const onceWords = [];
for (let [word, count] of counter) {
if (count === 1) onceWords.push(word);
}
return onceWords;
}
function getUncommonWords(onceWords, map) {
return onceWords.filter((onceWord) => !map.has(onceWord));
}
function uncommonFromSentences(s1, s2) {
const list1 = s1.split(' ');
const list2 = s2.split(' ');
const counter1 = buildCounter(list1);
const counter2 = buildCounter(list2);
const onceWords1 = getOnceWords(counter1);
const onceWords2 = getOnceWords(counter2);
return [
...getUncommonWords(onceWords1, counter2),
...getUncommonWords(onceWords2, counter1),
];
}
================================================
FILE: coding_interviews/leetcode/easy/unique-number-of-occurrences/unique-number-of-occurrences.js
================================================
function uniqueOccurrences(arr) {
const hashmap = new Map();
for (let num of arr) {
if (hashmap.has(num)) {
hashmap.set(num, hashmap.get(num) + 1);
} else {
hashmap.set(num, 1);
}
}
const counts = [];
hashmap.forEach((count, num) => {
counts.push(count);
});
return counts.length === new Set(counts).size;
}
================================================
FILE: coding_interviews/leetcode/easy/unique_morse_code_words.py
================================================
# https://leetcode.com/problems/unique-morse-code-words/description/
# "gin" -> "--...-."
# "zen" -> "--...-."
# "gig" -> "--...--."
# "msg" -> "--...--."
def unique_morse_representations(words):
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
alphabet = 'abcdefghijklmnopqrstuvwxyz'
morse_code_mapper = {}
for index, letter in enumerate(alphabet):
morse_code_mapper[letter] = morse[index]
unique_codes = set()
for word in words:
code = ''
for letter in word:
code += morse_code_mapper[letter]
unique_codes.add(code)
return len(unique_codes)
print(unique_morse_representations(["gin", "zen", "gig", "msg"]) == 2)
================================================
FILE: coding_interviews/leetcode/easy/unique_number_of_occurrences/unique_number_of_occurrences.py
================================================
# https://leetcode.com/problems/unique-number-of-occurrences
def unique_occurrences(arr):
num_to_occurrences = {}
for num in arr:
if num in num_to_occurrences:
num_to_occurrences[num] += 1
else:
num_to_occurrences[num] = 1
return len(num_to_occurrences) == len(set(num_to_occurrences.values()))
from collections import Counter
def unique_occurrences_2(arr):
num_to_occurrences = Counter(arr)
return len(num_to_occurrences) == len(set(num_to_occurrences.values()))
================================================
FILE: coding_interviews/leetcode/easy/univalued-binary-tree/univalued-binary-tree.js
================================================
function isUnivalTree(root) {
if (!root) return true;
const leftResult = isUnivalTree(root.left);
const rightResult = isUnivalTree(root.right);
let result = true;
result = root.left ? root.val === root.left.val : result;
result = root.right ? result && root.val === root.right.val : result;
return result && leftResult && rightResult;
}
function isUnivalTree(root, value = root.val) {
if (!root) return true;
return (
root.val === value &&
isUnivalTree(root.left, value) &&
isUnivalTree(root.right, value)
);
}
================================================
FILE: coding_interviews/leetcode/easy/valid-anagram/valid-anagram.js
================================================
function isAnagram(s, t) {
if (s.length !== t.length) {
return false;
}
let charCount = {};
for (let index = 0; index < s.length; index++) {
let char = s[index];
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
for (let char of t) {
if (charCount[char]) {
charCount[char]--;
} else {
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome-2.js
================================================
function isPalindrome(s) {
let string = s.toLowerCase().replace(/[^a-z0-9]/gi, '');
let start = 0;
let end = string.length - 1;
while (start <= end) {
if (string[start] !== string[end]) {
return false;
}
start++;
end--;
}
return true;
}
================================================
FILE: coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome.js
================================================
const alphanumeric = 'abcdefghijklmnopqrstuvwxyz0123456789';
function downcase(string) {
return string.toLowerCase();
}
function keepAlphanumeric(string) {
let alphanumericOnlyString = [];
for (let char of string) {
if (alphanumeric.includes(char)) {
alphanumericOnlyString.push(char);
}
}
return alphanumericOnlyString.join('');
}
function isValidPalindrome(string) {
let start = 0;
let end = string.length - 1;
while (start <= end) {
if (string[start] !== string[end]) {
return false;
}
start++;
end--;
}
return true;
}
function isPalindrome(string) {
return isValidPalindrome(keepAlphanumeric(downcase(string)));
}
================================================
FILE: coding_interviews/leetcode/easy/valid-palindrome/valid_palindrome.py
================================================
'''
Given a string, determine whether its palindrome if you are allowed to delete at most one character
Example
"aba" - True
"abca" - True
"abccadsfa" - False
"" - True
"abca" 0 => "bca"
"abca" 1 => "aca"
'''
# Brute force
def is_palindrome(string):
return string == string[::-1]
def build_new_string_variation(string, index):
return string[:index] + string[index+1:]
def valid_palindrome(string):
if string == '':
return True
if is_palindrome(string):
return True
for index in range(len(string)):
new_string = build_new_string_variation(string, index)
if is_palindrome(new_string):
return True
return False
data = [
("aba", True),
("abca", True),
("abccadsfa", False),
("", True)
]
for string, expected in data:
result = valid_palindrome(string)
print(result == expected)
# Greedy Solution: find if it is not palindrome
def valid_palindrome_2(string):
if string == '':
return True
if is_palindrome(string):
return True
for i in range(len(string) // 2):
last_current_index = len(string) - 1 - i
if string[i] != string[last_current_index]:
string_shifted_to_left = string[i:last_current_index]
string_shifted_to_right = string[i + 1:last_current_index + 1]
return is_palindrome(string_shifted_to_left) or is_palindrome(string_shifted_to_right)
return True
data = [
("aba", True),
("abc", False),
("abca", True),
("abccadsfa", False),
("", True)
]
for string, expected in data:
result = valid_palindrome_2(string)
print(result == expected)
================================================
FILE: coding_interviews/leetcode/easy/valid-parentheses/valid-parentheses.js
================================================
function matches(openBracket, closingBracket) {
return (
{
'}': '{',
']': '[',
')': '(',
}[closingBracket] === openBracket
);
}
function isValid(s) {
if (s.length === 1) {
return false;
}
const stack = [];
for (let char of s) {
if (['(', '{', '['].includes(char)) {
stack.push(char);
} else {
let top = stack.pop();
if (!matches(top, char)) {
return false;
}
}
}
return stack.length === 0;
}
================================================
FILE: coding_interviews/leetcode/easy/water-bottles/water-bottles.js
================================================
function numWaterBottles(numBottles, numExchange) {
let drinkNum = numBottles;
while (numBottles >= numExchange) {
let remainingBottles = numBottles % numExchange;
let newBottles = Math.floor(numBottles / numExchange);
drinkNum += newBottles;
numBottles = remainingBottles + newBottles;
}
return drinkNum;
}
================================================
FILE: coding_interviews/leetcode/easy/weakest_rows/weakest_rows.py
================================================
# https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix
def k_weakest_rows(mat, k):
sum_index_list = [[sum(row), index] for index, row in enumerate(mat)]
return [sum_index[1] for sum_index in sorted(sum_index_list)][:k]
================================================
FILE: coding_interviews/leetcode/easy/xor-operation-in-an-array/xor-operation-in-an-array.js
================================================
function xorOperation(n, start) {
let result = start;
let number = start;
for (let num = 1; num < n; num++) {
number += 2;
result ^= number;
}
return result;
}
================================================
FILE: coding_interviews/leetcode/medium/3sum/3sum-tle.js
================================================
function sortTriplet(num1, num2, num3) {
return [num1, num2, num3].sort((n1, n2) => n1 - n2);
}
function getSortedTripletString(num1, num2, num3) {
let triplet = sortTriplet(num1, num2, num3);
return `${triplet[0]}*${triplet[1]}*${triplet[2]}`;
}
function threeSum(nums) {
if (nums.length < 3) {
return [];
}
let triplets = [];
let numberCount = {};
let usedTriplets = {};
let usedPairs = {};
for (let num of nums) {
if (numberCount[num]) {
numberCount[num]++;
} else {
numberCount[num] = 1;
}
}
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
let num1 = nums[i];
let num2 = nums[j];
let pairSum = num1 + num2;
let missingTriplet = pairSum * -1;
let sortedPairString = `${Math.min(num1, num2)}*${Math.max(num1, num2)}`;
if (usedPairs[sortedPairString]) {
continue;
}
let sortedTripletString = getSortedTripletString(
num1,
num2,
missingTriplet
);
if (usedTriplets[sortedTripletString]) {
continue;
}
if (
(missingTriplet === num1 &&
missingTriplet === num2 &&
numberCount[missingTriplet] &&
numberCount[missingTriplet] >= 3) ||
(((missingTriplet === num1 && missingTriplet !== num2) ||
(missingTriplet !== num1 && missingTriplet === num2)) &&
numberCount[missingTriplet] &&
numberCount[missingTriplet] >= 2) ||
(missingTriplet !== num1 &&
missingTriplet !== num2 &&
numberCount[missingTriplet])
) {
triplets.push([num1, num2, missingTriplet]);
usedTriplets[sortedTripletString] = true;
usedPairs[sortedPairString] = true;
continue;
}
}
}
return triplets;
}
================================================
FILE: coding_interviews/leetcode/medium/add_two_numbers/add_two_numbers.py
================================================
# https://leetcode.com/problems/add-two-numbers/description/
'''
(1, 2, 3) + (2, 3, 4) = (3, 5, 7)
(1, 2, 3) + (2, 9, 4) = (3, 1, 8)
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def add_two_numbers(l1, l2):
carry = False
result_list = r_list = ListNode(0)
while l1 or l2 or carry:
if l1 and l2:
value = l1.val + l2.val
l1 = l1.next
l2 = l2.next
elif l1:
value = l1.val
l1 = l1.next
elif l2:
value = l2.val
l2 = l2.next
else:
value = 0
if carry:
value += 1
carry = False
if value >= 10:
value -= 10
carry = True
r_list.next = ListNode(value)
r_list = r_list.next
return result_list.next
# Test 1:
l1 = ListNode(1)
l1.next = ListNode(2)
l = l1.next
l.next = ListNode(3)
l2 = ListNode(2)
l2.next = ListNode(9)
l = l2.next
l.next = ListNode(4)
result_list = add_two_numbers(l1, l2)
while result_list:
print result_list.val
result_list = result_list.next
print "--------------------"
# Test 2:
l1 = ListNode(5)
l2 = ListNode(5)
result_list = add_two_numbers(l1, l2)
while result_list:
print result_list.val
result_list = result_list.next
================================================
FILE: coding_interviews/leetcode/medium/all_elements_in_two_binary_search_trees/all_elements_in_two_binary_search_trees.py
================================================
# https://leetcode.com/problems/all-elements-in-two-binary-search-trees
def get_all_elements(root1, root2):
values = []
get_sorted_list(root1, values)
get_sorted_list(root2, values)
return sorted(values)
def get_sorted_list(node, values):
if node.left:
get_sorted_list(node.left, values)
values.append(node.val)
if node.right:
get_sorted_list(node.right, values)
# ---------------------------------------------------------------------
def get_sorted_elements_from(node):
if not node:
return []
elements = []
if node.left:
elements = get_sorted_elements_from(node.left)
elements.append(node.val)
if node.right:
elements += get_sorted_elements_from(node.right)
return elements
def get_all_elements(root1, root2):
sorted_tree_1 = get_sorted_elements_from(root1)
sorted_tree_2 = get_sorted_elements_from(root2)
index_1, index_2 = 0, 0
result = []
while index_1 < len(sorted_tree_1) and index_2 < len(sorted_tree_2):
value1 = sorted_tree_1[index_1]
value2 = sorted_tree_2[index_2]
if value1 <= value2:
result.append(value1)
index_1 += 1
else:
result.append(value2)
index_2 += 1
if index_1 < len(sorted_tree_1):
result += sorted_tree_1[index_1:]
if index_2 < len(sorted_tree_2):
result += sorted_tree_2[index_2:]
return result
# ---------------------------------------------------------------------
def get_sorted_elements_from(node, elements):
if not node: return []
if node.left: get_sorted_elements_from(node.left, elements)
elements.append(node.val)
if node.right: get_sorted_elements_from(node.right, elements)
def get_all_elements(root1, root2):
sorted_tree_1 = []
get_sorted_elements_from(root1, sorted_tree_1)
sorted_tree_2 = []
get_sorted_elements_from(root2, sorted_tree_2)
index_1, index_2 = 0, 0
result = []
while index_1 < len(sorted_tree_1) and index_2 < len(sorted_tree_2):
value1 = sorted_tree_1[index_1]
value2 = sorted_tree_2[index_2]
if value1 <= value2:
result.append(value1)
index_1 += 1
else:
result.append(value2)
index_2 += 1
if index_1 < len(sorted_tree_1):
result += sorted_tree_1[index_1:]
if index_2 < len(sorted_tree_2):
result += sorted_tree_2[index_2:]
return result
================================================
FILE: coding_interviews/leetcode/medium/arithmetic-subarrays/arithmetic-subarrays.py
================================================
# https://leetcode.com/problems/arithmetic-subarrays
def check_arithmetic_subarrays(nums, l, r):
answer = []
for index in range(len(l)):
l_value = l[index]
r_value = r[index]
nums_range = sorted(nums[l_value:r_value+1])
is_arithmetic = True
diff = nums_range[1] - nums_range[0]
for i in range(2, len(nums_range)):
if diff != nums_range[i] - nums_range[i-1]:
is_arithmetic = False
break
answer.append(is_arithmetic)
return answer
================================================
FILE: coding_interviews/leetcode/medium/balance-a-binary-search-tree/balance-a-binary-search-tree.js
================================================
function inorder(root, nodes) {
if (root.left) inorder(root.left, nodes);
nodes.push(root.val);
if (root.right) inorder(root.right, nodes);
}
function toBST(start, end, nodes) {
if (start > end) return null;
const middle = Math.floor((start + end) / 2);
const bst = new TreeNode(nodes[middle]);
bst.left = toBST(start, middle - 1, nodes);
bst.right = toBST(middle + 1, end, nodes);
return bst;
}
function balanceBST(root) {
const nodes = [];
inorder(root, nodes);
return toBST(0, nodes.length - 1, nodes);
}
================================================
FILE: coding_interviews/leetcode/medium/binary-tree-inorder-traversal/binary-tree-inorder-traversal.py
================================================
# https://leetcode.com/problems/binary-tree-inorder-traversal
class Solution:
def __init__(self):
self.inorder_list = []
def inorder_traversal(self, root):
if root:
self.inorder_traversal(root.left)
self.inorder_list.append(root.val)
self.inorder_traversal(root.right)
return self.inorder_list
================================================
FILE: coding_interviews/leetcode/medium/binary-tree-level-order-traversal/binary-tree-level-order-traversal.js
================================================
function levelOrder(root) {
if (!root) {
return [];
}
let queue = [root];
let levelOrderTree = [];
while (queue.length) {
let levelNodes = [];
let levels = queue.length;
for (let level = 0; level < levels; level++) {
let node = queue.shift();
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
levelNodes.push(node.val);
}
levelOrderTree.push(levelNodes);
}
return levelOrderTree;
}
================================================
FILE: coding_interviews/leetcode/medium/bst_from_pre_order_traversal/bst_from_pre_order_traversal.py
================================================
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def bst_from_preorder(preorder):
root = TreeNode(preorder[0])
for value in preorder[1:]:
helper(root, value)
return root
def helper(node, value):
if value < node.val and node.left:
helper(node.left, value)
elif value < node.val:
node.left = TreeNode(value)
if value > node.val and node.right:
helper(node.right, value)
elif value > node.val:
node.right = TreeNode(value)
return node
================================================
FILE: coding_interviews/leetcode/medium/bst_to_greatest/bst_to_greatest.py
================================================
def sum_and_list(node, total, values):
left_total = 0
right_total = 0
left_values = []
right_values = []
if node.left:
[left_total, left_values] = sum_and_list(node.left, total, values)
if node.right:
[right_total, right_values] = sum_and_list(node.right, total, values)
return [
total + left_total + node.val + right_total,
values + left_values + [node.val] + right_values
]
def modify_helper(node, mapper):
if node.left:
modify_helper(node.left, mapper)
if node.right:
modify_helper(node.right, mapper)
node.val = mapper[node.val]
return node
def bst_to_gst(root):
[total, values] = sum_and_list(root, 0, [])
smaller_total = 0
mapper = {}
for value in values:
mapper[value] = total - smaller_total
smaller_total += value
return modify_helper(root, mapper)
value = 0
def bst_to_gst(node):
if node.right:
bst_to_gst(node.right)
node.val = node.val + value
value = node.val
if node.left:
bst_to_gst(node.left)
return node
================================================
FILE: coding_interviews/leetcode/medium/clone-graph/clone-graph.js
================================================
/*
Cloning a graph using a Breadth-First Search
— build a queue of all nodes in the graph
— build a hashmap of all cloned nodes
— if it's on the map: it's counted as visited & add to the neighbors' list
— else create from scratch
*/
function cloneGraph(node) {
if (!node) return;
let clonedGraph = new Node(node.val);
let queue = [node];
let createdNodes = {
1: clonedGraph,
};
while (queue.length) {
let currentNode = queue.shift();
let clonedNode = createdNodes[currentNode.val];
for (let neighbor of currentNode.neighbors) {
if (createdNodes[neighbor.val]) {
clonedNode.neighbors.push(createdNodes[neighbor.val]);
} else {
let createdNode = new Node(neighbor.val);
createdNodes[neighbor.val] = createdNode;
clonedNode.neighbors.push(createdNode);
queue.push(neighbor);
}
}
}
return clonedGraph;
}
================================================
FILE: coding_interviews/leetcode/medium/cloned_binary_tree/cloned_binary_tree.py
================================================
# https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
def get_target_copy(original, cloned, target):
if cloned.val == target.val:
return cloned
if cloned.left:
result = get_target_copy(original.left, cloned.left, target)
if result:
return result
if cloned.right:
result = get_target_copy(original.right, cloned.right, target)
if result:
return result
================================================
FILE: coding_interviews/leetcode/medium/count-nodes-equal-to-average-of-subtree/count-nodes-equal-to-average-of-subtree.js
================================================
function calculateAverage(totalValue, nodesCount) {
return Math.floor(totalValue / nodesCount);
}
function averageHelper(node, count) {
if (!node) {
return { totalValue: 0, nodesCount: 0, equalToAverageCount: 0 };
}
const left = averageHelper(node.left, 1);
const right = averageHelper(node.right, 1);
const totalValue = node.val + left.totalValue + right.totalValue;
const nodesCount = count + left.nodesCount + right.nodesCount;
const average = calculateAverage(totalValue, nodesCount);
const equalToAverageCount =
(average === node.val ? 1 : 0) +
left.equalToAverageCount +
right.equalToAverageCount;
return {
totalValue,
nodesCount,
equalToAverageCount,
};
}
function averageOfSubtree(root) {
let totalValue = root.val;
let nodesCount = 1;
const left = averageHelper(root.left, nodesCount);
const right = averageHelper(root.right, nodesCount);
const average = calculateAverage(
totalValue + left.totalValue + right.totalValue,
nodesCount + left.nodesCount + right.nodesCount
);
return (
(average === root.val ? 1 : 0) +
left.equalToAverageCount +
right.equalToAverageCount
);
}
================================================
FILE: coding_interviews/leetcode/medium/count-number-of-distinct-integers-after-reverse-operations/count-number-of-distinct-integers-after-reverse-operations-numbers.js
================================================
// https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations
function reverseDigits(num) {
let digits = 0;
while (num > 0) {
digits = digits * 10 + (num % 10);
num = Math.floor(num / 10);
}
return digits;
}
function countDistinctIntegers(nums) {
let set = new Set();
let N = nums.length;
for (let index = 0; index < N; index++) {
let num = nums[index];
set.add(num);
let reversedDigitsNum = reverseDigits(num);
set.add(reversedDigitsNum);
}
return set.size;
}
================================================
FILE: coding_interviews/leetcode/medium/count-number-of-distinct-integers-after-reverse-operations/count-number-of-distinct-integers-after-reverse-operations.js
================================================
// https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations
function reverseDigits(num) {
let digits = [];
while (num > 0) {
digits.push((num % 10).toString());
num = Math.floor(num / 10);
}
return Number(digits.join(''));
}
function countDistinctIntegers(nums) {
let set = new Set();
let N = nums.length;
for (let index = 0; index < N; index++) {
let num = nums[index];
set.add(num);
let reversedDigitsNum = reverseDigits(num);
set.add(reversedDigitsNum);
}
return set.size;
}
================================================
FILE: coding_interviews/leetcode/medium/count-sorted-vowel-strings/count-sorted-vowel-strings.js
================================================
function countVowelStrings(n) {
let a = 1,
e = 1,
i = 1,
o = 1,
u = 1;
for (let counter = 1; counter < n; counter++) {
o += u;
i += o;
e += i;
a += e;
}
return a + e + i + o + u;
}
================================================
FILE: coding_interviews/leetcode/medium/count-sub-islands/count-sub-islands-tle.js
================================================
/**
- getting all islands in grid2
- store the rows and columns of each island
- this can be stored in a list
- e.g. [[[3,0]], [[4,1]], [2,1]]
- iterate through the list of islands of grid2
- if all rows and cols from an island of grid2 match the cells in the grid1
- increment the number of sub-islands
- return number of sub islands
*/
function isInsideTheGrid(grid, row, col) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;
}
function dfs(grid, row, col) {
if (!isInsideTheGrid(grid, row, col)) {
return [];
}
if (grid[row][col]) {
grid[row][col] = 0;
return [
[row, col],
...dfs(grid, row - 1, col),
...dfs(grid, row + 1, col),
...dfs(grid, row, col - 1),
...dfs(grid, row, col + 1),
];
}
return [];
}
function countSubIslands(grid1, grid2) {
let islands = [];
for (let row = 0; row < grid2.length; row++) {
for (let col = 0; col < grid2[row].length; col++) {
let cell = grid2[row][col];
if (cell) {
grid2[row][col] = 0;
let island = [
[row, col],
...dfs(grid2, row - 1, col),
...dfs(grid2, row + 1, col),
...dfs(grid2, row, col - 1),
...dfs(grid2, row, col + 1),
];
islands.push(island);
}
}
}
let numberOfSubIslands = 0;
for (let island of islands) {
let isSubIsland = true;
for (let [row, col] of island) {
if (grid1[row][col] === 0) {
isSubIsland = false;
break;
}
}
if (isSubIsland) {
numberOfSubIslands++;
}
}
return numberOfSubIslands;
}
================================================
FILE: coding_interviews/leetcode/medium/count-sub-islands/count-sub-islands.js
================================================
function dfs(grid1, grid2, row, col) {
if (
row < 0 ||
row >= grid2.length ||
col < 0 ||
col >= grid2[0].length ||
grid2[row][col] == 0
) {
return 1;
}
grid2[row][col] = 0;
let numberOfSubIslands = 1;
numberOfSubIslands &= dfs(grid1, grid2, row - 1, col);
numberOfSubIslands &= dfs(grid1, grid2, row + 1, col);
numberOfSubIslands &= dfs(grid1, grid2, row, col - 1);
numberOfSubIslands &= dfs(grid1, grid2, row, col + 1);
return numberOfSubIslands & grid1[row][col];
}
function countSubIslands(grid1, grid2) {
let numberOfSubIslands = 0;
for (let row = 0; row < grid2.length; row++) {
for (let col = 0; col < grid2[row].length; col++) {
if (grid2[row][col]) {
numberOfSubIslands += dfs(grid1, grid2, row, col);
}
}
}
return numberOfSubIslands;
}
================================================
FILE: coding_interviews/leetcode/medium/count_points/count_points.py
================================================
# https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle
def is_point_within_circuference(qx, qy, qr, px, py):
return qr ** 2 >= abs(qx - px) ** 2 + abs(qy - py) ** 2
def count_points(points, queries):
answer = []
for [qx, qy, qr] in queries:
count = 0
for [px, py] in points:
if is_point_within_circuference(qx, qy, qr, px, py):
count += 1
answer.append(count)
return answer
================================================
FILE: coding_interviews/leetcode/medium/counter_number_of_teams/counter_number_of_teams.py
================================================
def num_teams(rating):
counter = 0
for i in range(len(rating) - 2):
for j in range(i + 1, len(rating) - 1):
for k in range(j + 1, len(rating)):
if (rating[i] < rating[j] and rating[j] < rating[k]) or (
rating[i] > rating[j] and rating[j] > rating[k]):
counter += 1
return counter
def num_teams(rating):
asc = desc = 0
for index, value in enumerate(rating):
llc = rgc = lgc = rlc = 0
for left in rating[:index]:
if left > value:
lgc += 1
if left < value:
llc += 1
for right in rating[index + 1:]:
if right > value:
rgc += 1
if right < value:
rlc += 1
asc += llc * rgc
desc += lgc * rlc
return asc + desc
================================================
FILE: coding_interviews/leetcode/medium/deck_revealed_increasing/deck_revealed_increasing.py
================================================
# https://leetcode.com/problems/reveal-cards-in-increasing-order
import queue
def deck_revealed_increasing(deck):
q = queue.Queue()
sorted_deck = sorted(deck)
for index in range(len(deck)): q.put(index)
result = [0] * len(deck)
index = 0
while not q.empty():
result[q.get()] = sorted_deck[index]
index += 1
if not q.empty(): q.put(q.get())
return result
================================================
FILE: coding_interviews/leetcode/medium/decode-string/decode-string.js
================================================
const isNum = (char) => !isNaN(Number(char));
export function decodeString(encodedString) {
const stack = [];
let index = 0;
while (index < encodedString.length) {
const char = encodedString[index];
if (isNum(char)) {
const number = [];
while (isNum(encodedString[index])) {
number.push(encodedString[index]);
index++;
}
stack.push(Number(number.join('')));
continue;
}
if (char === ']') {
let str = '';
while (stack[stack.length - 1] !== '[') {
str = stack.pop() + str;
}
stack.pop();
stack.push(str.repeat(stack.pop()));
index++;
continue;
}
stack.push(char);
index++;
}
return stack.join('');
}
================================================
FILE: coding_interviews/leetcode/medium/decode-string/tests/decode-string.test.js
================================================
import { describe, it, expect } from 'vitest';
import { decodeString } from '../decode-string';
describe('decodeString', () => {
it('', () => {
expect(decodeString('3[a]2[bc]')).toEqual('aaabcbc');
});
it('', () => {
expect(decodeString('2[abc]3[cd]ef')).toEqual('abcabccdcdcdef');
});
it('', () => {
expect(decodeString('3[a2[c]]')).toEqual('accaccacc');
});
it('', () => {
expect(decodeString('100[leetcode]')).toEqual(
'leetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcode'
);
});
});
================================================
FILE: coding_interviews/leetcode/medium/deepest_leaves_sum/deepest_leaves_sum.py
================================================
# https://leetcode.com/problems/deepest-leaves-sum
'''
Given a binary tree, return the sum of values of its deepest leaves.
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
'''
def sum_deepest_leaves(root):
mapper = helper(root, {}, 1)
deepest_level = 1
for level in mapper:
if level > deepest_level:
deepest_level = level
deepest_level_nodes_values = mapper[deepest_level]
nodes_values_sum = 0
for node_value in deepest_level_nodes_values:
nodes_values_sum += node_value
return nodes_values_sum
def helper(node, mapper, level):
if level in mapper:
mapper[level] = mapper[level] + [node.val]
else:
mapper[level] = [node.val]
if node.left:
mapper = helper(node.left, mapper, level + 1)
if node.right:
mapper = helper(node.right, mapper, level + 1)
return mapper
================================================
FILE: coding_interviews/leetcode/medium/delete-node-in-a-linked-list/better-delete-node-in-a-linked-list.js
================================================
// https://leetcode.com/problems/delete-node-in-a-linked-list
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
* @param {ListNode} node
* @return {void} Do not return anything, modify node in-place instead.
*/
function deleteNode(node) {
node.val = node.next.val;
node.next = node.next.next;
}
================================================
FILE: coding_interviews/leetcode/medium/delete-node-in-a-linked-list/delete-node-in-a-linked-list.js
================================================
// https://leetcode.com/problems/delete-node-in-a-linked-list
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
* @param {ListNode} node
* @return {void} Do not return anything, modify node in-place instead.
*/
function deleteNode(node) {
if (node.next && !node.next.next) {
node.val = node.next.val;
node.next = null;
return;
}
node.val = node.next.val;
deleteNode(node.next);
}
================================================
FILE: coding_interviews/leetcode/medium/design-a-stack-with-increment-operation/design-a-stack-with-increment-operation.js
================================================
export const CustomStack = function (maxSize) {
this.maxSize = maxSize;
this.items = [];
};
CustomStack.prototype.push = function (x) {
if (this.items.length < this.maxSize) {
this.items.push(x);
}
};
CustomStack.prototype.pop = function () {
return this.items.length > 0 ? this.items.pop() : -1;
};
CustomStack.prototype.increment = function (k, val) {
for (let i = 0; i < k; i++) {
if (i <= this.items.length - 1) this.items[i] += val;
}
};
================================================
FILE: coding_interviews/leetcode/medium/design-a-stack-with-increment-operation/tests/design-a-stack-with-increment-operation.test.js
================================================
import { describe, expect, it } from 'vitest';
import { CustomStack } from '../design-a-stack-with-increment-operation';
describe('CustomStack', () => {
it('', () => {
const customStack = new CustomStack(3);
customStack.push(1);
customStack.push(2);
expect(customStack.pop()).toEqual(2);
customStack.push(2);
customStack.push(3);
customStack.push(4);
customStack.increment(5, 100);
customStack.increment(2, 100);
expect(customStack.pop()).toEqual(103);
expect(customStack.pop()).toEqual(202);
expect(customStack.pop()).toEqual(201);
expect(customStack.pop()).toEqual(-1);
});
});
================================================
FILE: coding_interviews/leetcode/medium/design-add-and-search-words-data-structure/design-add-and-search-words-data-structure.js
================================================
function isTheSame(word, wordFromDict) {
if (word.length !== wordFromDict.length) return false;
for (let index = 0; index < word.length; index++) {
let wordChar = word[index];
let wordFromDictChar = wordFromDict[index];
if (wordChar === '.') {
continue;
}
if (wordChar !== wordFromDictChar) {
return false;
}
}
return true;
}
const WordDictionary = function () {
this.hashmap = {};
};
WordDictionary.prototype.addWord = function (word) {
if (!this.hashmap[word]) {
this.hashmap[word] = true;
}
};
WordDictionary.prototype.search = function (word) {
if (this.hashmap[word]) {
return this.hashmap[word];
}
let words = Object.keys(this.hashmap);
for (let wordFromDict of words) {
if (isTheSame(word, wordFromDict)) {
return true;
}
}
return false;
};
================================================
FILE: coding_interviews/leetcode/medium/difference-between-ones-and-zeros-in-row-and-column/difference-between-ones-and-zeros-in-row-and-column.js
================================================
function traverseGridRow(grid, row) {
let diff = 0;
for (let col = 0; col < grid[row].length; col++) {
let cell = grid[row][col];
if (cell) {
diff++;
} else {
diff--;
}
}
return diff;
}
function traverseGridCol(grid, col) {
let diff = 0;
for (let row = 0; row < grid.length; row++) {
let cell = grid[row][col];
if (cell) {
diff++;
} else {
diff--;
}
}
return diff;
}
function onesMinusZeros(grid) {
let rows = [];
let cols = [];
let diffGrid = [];
for (let row = 0; row < grid.length; row++) {
let diffRow = [];
for (let col = 0; col < grid[row].length; col++) {
let rowDiff;
let colDiff;
if (row < rows.length) {
rowDiff = rows[row];
} else {
rowDiff = traverseGridRow(grid, row);
rows.push(rowDiff);
}
if (col < cols.length) {
colDiff = cols[col];
} else {
colDiff = traverseGridCol(grid, col);
cols.push(colDiff);
}
diffRow.push(rowDiff + colDiff);
}
diffGrid.push(diffRow);
}
return diffGrid;
}
================================================
FILE: coding_interviews/leetcode/medium/encode_and_decode_tinyurl/encode_and_decode_tinyurl.py
================================================
# https://leetcode.com/problems/encode-and-decode-tinyurl
class Codec:
count = 0
tiny_to_url = {}
url_to_tiny = {}
tiny_url_prefix = 'http://tinyurl.com/'
def encode(self, longUrl: str) -> str:
if longUrl in self.url_to_tiny:
return self.url_to_tiny[longUrl]
tiny_url = self.tiny_url_prefix + str(self.count)
self.url_to_tiny[longUrl] = tiny_url
self.tiny_to_url[tiny_url] = longUrl
self.count += 1
return tiny_url
def decode(self, shortUrl: str) -> str:
return self.tiny_to_url[shortUrl]
================================================
FILE: coding_interviews/leetcode/medium/execution-of-all-suffix-instructions-staying-in-a-grid/execution-of-all-suffix-instructions-staying-in-a-grid.js
================================================
// https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid
function isOffGrid(row, col, n) {
return row < 0 || row >= n || col < 0 || col >= n;
}
function executeInstructions(n, startPos, s) {
let answer = [];
for (let index = 0; index < s.length; index++) {
let instructionIndex = index;
let instruction = s[instructionIndex];
let row = startPos[0];
let col = startPos[1];
let numOfInstructions = 0;
if (instruction === 'R') col++;
if (instruction === 'L') col--;
if (instruction === 'U') row--;
if (instruction === 'D') row++;
while (instructionIndex < s.length && !isOffGrid(row, col, n)) {
instructionIndex++;
instruction = s[instructionIndex];
if (instruction === 'R') col++;
if (instruction === 'L') col--;
if (instruction === 'U') row--;
if (instruction === 'D') row++;
numOfInstructions++;
}
answer.push(numOfInstructions);
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/medium/find-the-original-array-of-prefix-xor/README.md
================================================
# Find The Original Array of Prefix Xor
[Problem link](https://leetcode.com/problems/find-the-original-array-of-prefix-xor)
- If you want `5 ^ ? = 2`, you can do a reverse xor using `5 ^ 2 = ?`, which in this case `? = 7`
- If you want to do consecutive XOR operations like `5 ^ 7 ^ 2 ^ 3 ^ 2`, you can replace that with the previous `pref` item
- e.g. `5 ^ 7 ^ ? = 0.`, you want to find `?`
- so you need to do `5 ^ 7 ^ 0 = ?` but at that point, if you don't store the previous result, you don't have `5 ^ 7`
- but you can get this calculation from the previous `pref` item because it can replace `5 ^ 7`, in this case, it is `2`
- Runtime complexity: O(N), where N is prev.length
================================================
FILE: coding_interviews/leetcode/medium/find-the-original-array-of-prefix-xor/find-the-original-array-of-prefix-xor.js
================================================
function findArray(pref) {
let output = [pref[0]];
for (let index = 1; index < pref.length; index++) {
output.push(pref[index - 1] ^ pref[index]);
}
return output;
}
================================================
FILE: coding_interviews/leetcode/medium/find-the-winner-of-the-circular-game/find-the-winner-of-the-circular-game.js
================================================
// https://leetcode.com/problems/find-the-winner-of-the-circular-game
function toArray(n) {
let list = [];
for (let num = 1; num <= n; num++) {
list.push(num);
}
return list;
}
function findTheWinner(n, k) {
let list = toArray(n);
let index = 0;
while (list.length > 1) {
index = (index + k - 1) % list.length;
list.splice(index, 1);
}
return list[0];
}
================================================
FILE: coding_interviews/leetcode/medium/find-the-winner-of-the-circular-game/queue-find-the-winner-of-the-circular-game.js
================================================
// https://leetcode.com/problems/find-the-winner-of-the-circular-game
function buildQueue(n) {
let queue = [];
for (let num = 1; num <= n; num++) {
queue.push(num);
}
return queue;
}
function findTheWinner(n, k) {
let queue = buildQueue(n);
while (queue.length > 1) {
let count = 1;
while (count < k) {
queue.push(queue.shift());
count++;
}
queue.shift();
}
return queue[0];
}
================================================
FILE: coding_interviews/leetcode/medium/find-triangular-sum-of-an-array/find-triangular-sum-of-an-array.js
================================================
function calculate(num1, num2) {
return (num1 + num2) % 10;
}
export function triangularSum(nums) {
let numsCopy = [...nums];
let newNums = [];
let N = nums.length;
for (let i = 0; i < N - 1; i++) {
newNums = [];
for (let index = 0; index < numsCopy.length - 1; index++) {
newNums.push(calculate(numsCopy[index], numsCopy[index + 1]));
}
numsCopy = newNums;
}
return numsCopy;
}
================================================
FILE: coding_interviews/leetcode/medium/find-triangular-sum-of-an-array/tests/find-triangular-sum-of-an-array.test.js
================================================
import { describe, expect, it } from 'vitest';
import { triangularSum } from '../find-triangular-sum-of-an-array';
describe('triangularSum', () => {
it('', () => {
expect(triangularSum([1, 2, 3, 4, 5])).toEqual([8]);
});
it('', () => {
expect(triangularSum([5])).toEqual([5]);
});
});
================================================
FILE: coding_interviews/leetcode/medium/find-valid-matrix-given-row-and-column-sums/find-valid-matrix-given-row-and-column-sums.js
================================================
function buildMatrix(rows, cols) {
const matrix = [];
for (let row = 0; row < rows; row++) {
let matrixRow = [];
for (let col = 0; col < cols; col++) {
matrixRow.push(0);
}
matrix.push(matrixRow);
}
return matrix;
}
function restoreMatrix(rowSum, colSum) {
const matrix = buildMatrix(rowSum.length, colSum.length);
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[0].length; col++) {
const min = Math.min(rowSum[row], colSum[col]);
matrix[row][col] = min;
rowSum[row] -= min;
colSum[col] -= min;
}
}
return matrix;
}
================================================
FILE: coding_interviews/leetcode/medium/find_and_replace_pattern/find_and_replace_pattern.py
================================================
# https://leetcode.com/problems/find-and-replace-pattern
def find_and_replace_pattern(words, pattern):
matchers = []
for word in words:
mapper = {}
match = True
used_pattern_letters = set()
for index in range(len(word)):
word_letter = word[index]
pattern_letter = pattern[index]
if word_letter in mapper and mapper[word_letter] != pattern_letter or (pattern_letter in used_pattern_letters and word_letter not in mapper):
match = False
break
if word_letter not in mapper:
used_pattern_letters.add(pattern_letter)
mapper[word_letter] = pattern_letter
if match: matchers.append(word)
return matchers
================================================
FILE: coding_interviews/leetcode/medium/finding_pairs_with_a_certain_sum/finding_pairs_with_a_certain_sum.py
================================================
# https://leetcode.com/problems/finding-pairs-with-a-certain-sum
class FindSumPairs:
def __init__(self, nums1, nums2):
self.nums1 = nums1
self.nums2 = nums2
self.nums2_freq = Counter(nums2)
def add(self, index, val):
self.nums2_freq[self.nums2[index]] -= 1
self.nums2[index] += val
self.nums2_freq[self.nums2[index]] += 1
def count(self, total):
count = 0
for num in self.nums1:
if (total - num) in self.nums2_freq:
count += self.nums2_freq[total - num]
return count
================================================
FILE: coding_interviews/leetcode/medium/finding_the_users_active_minutes/finding_the_users_active_minutes.py
================================================
# https://leetcode.com/problems/finding-the-users-active-minutes
def build_unique_actions_by_id(logs):
unique_actions_by_id = {}
for [id, minute] in logs:
if id in unique_actions_by_id:
unique_actions_by_id[id].add(minute)
else:
unique_actions_by_id[id] = set({minute})
return unique_actions_by_id
def build_count_by_actions_number(unique_actions_by_id):
count = {}
for _, actions in unique_actions_by_id.items():
if len(actions) in count:
count[len(actions)] += 1
else:
count[len(actions)] = 1
return count
def build_answer(count_by_actions_number, k):
answer = []
for num in range(1, k + 1):
if num in count_by_actions_number:
answer.append(count_by_actions_number[num])
else:
answer.append(0)
return answer
def finding_users_active_minutes(logs, k):
unique_actions_by_id = build_unique_actions_by_id(logs)
count_by_actions_number = build_count_by_actions_number(unique_actions_by_id)
return build_answer(count_by_actions_number, k)
# -------------------------------------------------------------------------------
def finding_users_active_minutes(logs, k):
d = defaultdict(set)
for id, minute in logs:
d[id].add(minute)
answer = [0] * k
for _, actions in d.items():
count = len(actions)
answer[count - 1] += 1
return answer
================================================
FILE: coding_interviews/leetcode/medium/fraction_to_decimal/fraction_to_decimal.py
================================================
def fraction_to_decimal(numerator, denominator):
if numerator == 0:
return '0'
if numerator % denominator == 0:
return str(numerator // denominator)
result = ''
if ('-' in str(numerator)) ^ ('-' in str(denominator)):
result += '-'
numerator = abs(numerator)
denominator = abs(denominator)
number = str(numerator // denominator)
result += number
result += '.'
mapper = {}
remainder = numerator % denominator
while True:
if remainder == 0:
break
if remainder in mapper:
result = result[:mapper[remainder]] + \
'(' + result[mapper[remainder]:] + ')'
break
mapper[remainder] = len(result)
remainder *= 10
result += str(remainder // denominator)
remainder %= denominator
return result
data_test = [
(1, 2, "0.5"),
(2, 1, "2"),
(2, 3, "0.(6)"),
(4, 333, "0.(012)"),
(1, 4, "0.25"),
(1, 6, "0.1(6)"),
(-1, 6, "-0.1(6)"),
(1, -6, "-0.1(6)"),
(-50, 8, "-6.25"),
(1, 214748364, "0.00(000000465661289042462740251655654056577585848337359161441621040707904997124914069194026549138227660723878669455195477065427143370461252966751355553982241280310754777158628319049732085502639731402098131932683780538602845887105337854867197032523144157689601770377165713821223802198558308923834223016478952081795603341592860749337303449725)")
]
for numerator, denominator, expected in data_test:
result = fraction_to_decimal(numerator, denominator)
print(result, result == expected)
================================================
FILE: coding_interviews/leetcode/medium/group-anagrams/group-anagrams.js
================================================
function sort(string) {
return [...string].sort((c1, c2) => c1.localeCompare(c2)).join('');
}
function groupAnagrams(strs) {
let hashmap = {};
for (let string of strs) {
let sortedString = sort(string);
if (hashmap[sortedString]) {
hashmap[sortedString].push(string);
} else {
hashmap[sortedString] = [string];
}
}
return Object.values(hashmap);
}
================================================
FILE: coding_interviews/leetcode/medium/group_the_people/group_the_people.py
================================================
# https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/
def group_the_people(groupSizes):
grouped_by_size = {}
for index in range(len(groupSizes)):
size = groupSizes[index]
if size in grouped_by_size:
grouped_by_size[size] += [index]
else:
grouped_by_size[size] = [index]
grouped_by_ids = []
for size, indices in grouped_by_size.items():
for index in range(0, len(indices), size):
grouped_by_ids.append(indices[index:index+size])
return grouped_by_ids
================================================
FILE: coding_interviews/leetcode/medium/insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.js
================================================
/**
* https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list
*
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
function calculateGCD(x, y) {
x = Math.abs(x);
y = Math.abs(y);
while (y) {
var t = y;
y = x % y;
x = t;
}
return x;
}
function insertGreatestCommonDivisors(head) {
if (!head.next) return head;
let curr = head;
let next = head.next;
while (next) {
let newNode = new ListNode(calculateGCD(curr.val, next.val), next);
curr.next = newNode;
curr = next;
next = next.next;
}
return head;
}
================================================
FILE: coding_interviews/leetcode/medium/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.js
================================================
function insertIntoBST(root, val) {
if (!root) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
}
if (val > root.val) {
root.right = insertIntoBST(root.right, val);
}
return root;
}
================================================
FILE: coding_interviews/leetcode/medium/insert_bst/insert_bst.py
================================================
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_BST(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_into_BST(root.left, val)
if val > root.val:
root.right = insert_into_BST(root.right, val)
return root
================================================
FILE: coding_interviews/leetcode/medium/keep_city_skyline/keep_city_skyline.py
================================================
# https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/
# input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
# output: 35
def build_top_or_bottom(grid):
top_or_bottom = []
for i in range(len(grid[0])):
highest_building = 0
for j in range(len(grid)):
if grid[j][i] > highest_building:
highest_building = grid[j][i]
top_or_bottom.append(highest_building)
return top_or_bottom
def build_left_or_right(grid):
left_or_right = []
for line in grid:
highest_building = 0
for building_height in line:
if building_height > highest_building:
highest_building = building_height
left_or_right.append(highest_building)
return left_or_right
def max_increase_keeping_skyline(grid):
top_or_bottom = build_top_or_bottom(grid)
left_or_right = build_left_or_right(grid)
increased_number = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if left_or_right[i] < top_or_bottom[j]:
increased_number += (left_or_right[i] - grid[i][j])
else:
increased_number += (top_or_bottom[j] - grid[i][j])
return increased_number
print(max_increase_keeping_skyline([[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]))
================================================
FILE: coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-1.js
================================================
function traverse(node, list) {
return node
? [
...list,
...traverse(node.left, list),
node.val,
...traverse(node.right, list),
]
: [];
}
function kthSmallest(root, k) {
return traverse(root, [])[k - 1];
}
================================================
FILE: coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-2.js
================================================
let counter;
let nodeValue;
function traverseAndGetKthSmallest(node, k) {
if (!node) return;
traverseAndGetKthSmallest(node.left, k);
counter++;
if (counter === k) {
nodeValue = node.val;
}
traverseAndGetKthSmallest(node.right, k);
}
function kthSmallest(root, k) {
counter = 0;
nodeValue = -1;
traverseAndGetKthSmallest(root, k);
return nodeValue;
}
================================================
FILE: coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.js
================================================
// Solution 1
// additional memory usage: array
function traverse(node, list) {
return node
? [
...list,
...traverse(node.left, list),
node.val,
...traverse(node.right, list),
]
: [];
}
function kthSmallest(root, k) {
return traverse(root, [])[k - 1];
}
// =========================== // ===========================
// Solution 2
// Less memory
let counter;
let nodeValue;
function traverseAndGetKthSmallest(node, k) {
if (!node) return;
traverseAndGetKthSmallest(node.left, k);
counter++;
if (counter === k) {
nodeValue = node.val;
}
traverseAndGetKthSmallest(node.right, k);
}
function kthSmallest(root, k) {
counter = 0;
nodeValue = -1;
traverseAndGetKthSmallest(root, k);
return nodeValue;
}
================================================
FILE: coding_interviews/leetcode/medium/letter_tile_possibilities/letter_tile_possibilities.py
================================================
# https://leetcode.com/problems/letter-tile-possibilities
def num_tile_possibilities(tiles):
res = set()
def dfs(path, tile):
if path not in res:
if path: res.add(path)
for i in range(len(tile)):
dfs(path + tile[i], tile[:i] + tile[i+1:])
dfs('', tiles)
return len(res)
================================================
FILE: coding_interviews/leetcode/medium/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js
================================================
/**
abcadccb => abc / bcad / cad / adc / dc / c / cb
=> 4
"abcadccb"
^ ^
localCount = 0 -> 1 -> 2 -> 1 -> 2 -> 3;
maxCount = 0 -> 1 -> 2 -> 3;
set = ['b', 'c'] -> ['c', 'd', 'a'] -> ['c', 'd', 'a', 'b']
*/
function lengthOfLongestSubstring(s) {
let leftPointer = 0;
let maxCount = 0;
let charToIndex = {};
for (let rightPointer = 0; rightPointer < s.length; rightPointer++) {
let num = s[rightPointer];
let index = charToIndex[num];
if (index == undefined) {
maxCount = Math.max(maxCount, rightPointer - leftPointer + 1);
} else {
if (index >= leftPointer) {
leftPointer = index + 1;
} else {
maxCount = Math.max(maxCount, rightPointer - leftPointer + 1);
}
}
charToIndex[num] = rightPointer;
}
return maxCount;
}
================================================
FILE: coding_interviews/leetcode/medium/max-area-of-island/max-area-of-island.js
================================================
function isOffTheGrid(grid, row, col) {
let gridRows = grid.length;
let gridCols = grid[0].length;
return row < 0 || row >= gridRows || col < 0 || col >= gridCols;
}
function dfs(grid, row, col, maximumLocalIslandArea = 0) {
if (isOffTheGrid(grid, row, col) || grid[row][col] === 0) {
return 0;
}
grid[row][col] = 0; // visited
return (
1 +
dfs(grid, row - 1, col, maximumLocalIslandArea) + // top
dfs(grid, row + 1, col, maximumLocalIslandArea) + // bottom
dfs(grid, row, col + 1, maximumLocalIslandArea) + // right
dfs(grid, row, col - 1, maximumLocalIslandArea) // left
);
}
function maxAreaOfIsland(grid) {
let maximumIslandArea = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
let maximumLocalIslandArea = dfs(grid, row, col);
maximumIslandArea = Math.max(maximumIslandArea, maximumLocalIslandArea);
}
}
return maximumIslandArea;
}
================================================
FILE: coding_interviews/leetcode/medium/max_coins/max_coins.py
================================================
# https://leetcode.com/problems/maximum-number-of-coins-you-can-get
def max_coins(piles):
piles = sorted(piles)
bob = 0
me = len(piles) - 2
alice = len(piles) - 1
counter = 0
while me > bob:
counter += piles[me]
bob += 1
me -= 2
alice -= 2
return counter
================================================
FILE: coding_interviews/leetcode/medium/maximum-sum-of-an-hourglass/maximum-sum-of-an-hourglass.js
================================================
// https://leetcode.com/problems/maximum-sum-of-an-hourglass
function maxRowSum(grid, row, col) {
return (
grid[row][col] +
grid[row][col + 1] +
grid[row][col + 2] +
grid[row + 1][col + 1] +
grid[row + 2][col] +
grid[row + 2][col + 1] +
grid[row + 2][col + 2]
);
}
function maxSum(grid) {
let maxSumOfAnHourglass = 0;
for (let row = 0; row + 2 < grid.length; row++) {
for (let col = 0; col + 2 < grid[row].length; col++) {
maxSumOfAnHourglass = Math.max(
maxSumOfAnHourglass,
maxRowSum(grid, row, col)
);
}
}
return maxSumOfAnHourglass;
}
================================================
FILE: coding_interviews/leetcode/medium/maximum_binary_tree/maximum_binary_tree.py
================================================
'''
https://leetcode.com/problems/maximum-binary-tree/description/
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def construct_maximum_binary_tree(nums):
if not nums: return None
root_node = TreeNode(max(nums))
root_node.left = construct_maximum_binary_tree(nums[0:nums.index(max(nums))])
root_node.right = construct_maximum_binary_tree(nums[nums.index(max(nums))+1:])
return root_node
================================================
FILE: coding_interviews/leetcode/medium/median_tree/median_tree.py
================================================
class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def sum_and_count_nodes(node, sum_of_values, count):
if node is None:
return sum_of_values, count
sum_of_values, count = sum_and_count_nodes(node.left, sum_of_values + node.value, count + 1)
sum_of_values, count = sum_and_count_nodes(node.right, sum_of_values + node.value, count + 1)
return sum_of_values, count
def median(tree):
sum_of_values, count = sum_and_count_nodes(tree, 0, 0)
if count == 0: return 0
return sum_of_values / count
left = Node(1, None, None)
right = Node(2, None, None)
root = Node(3, left, right)
result = median(root)
print(result)
================================================
FILE: coding_interviews/leetcode/medium/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js
================================================
export class ListNode {
constructor(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
export function mergeNodes(head) {
let nonZeroHead;
let node;
let nextNode;
let currentNode = head.next;
let valueSum = 0;
let gotFirstNode = false;
while (currentNode) {
valueSum += currentNode.val;
if (currentNode.val === 0) {
nextNode = new ListNode(valueSum);
valueSum = 0;
if (gotFirstNode) {
node.next = nextNode;
node = node.next;
} else {
node = nextNode;
nonZeroHead = nextNode;
gotFirstNode = true;
}
}
currentNode = currentNode.next;
}
return nonZeroHead;
}
================================================
FILE: coding_interviews/leetcode/medium/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js
================================================
import { describe, it, expect } from 'vitest';
import { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros';
function buildList(nums, initValue = 0) {
let head = new ListNode(initValue);
let node = head;
let nextNode;
for (let i = 1; i < nums.length; i++) {
nextNode = new ListNode(nums[i]);
node.next = nextNode;
node = node.next;
}
return head;
}
describe('mergeNodes', () => {
it('removes zeros and merges nodes', () => {
const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]);
const result = buildList([4, 11], 4);
expect(mergeNodes(head)).toEqual(result);
});
it('removes zeros and merges nodes', () => {
const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]);
const result = buildList([1, 3, 4], 1);
expect(mergeNodes(head)).toEqual(result);
});
});
================================================
FILE: coding_interviews/leetcode/medium/min-cost-climbing-stairs/min-cost-climbing-stairs.js
================================================
// https://leetcode.com/problems/min-cost-climbing-stairs
// https://leetcode.com/problems/min-cost-climbing-stairs/solutions/476388/4-ways-step-by-step-from-recursion-top-down-dp-bottom-up-dp-fine-tuning
function getMinCost(stairs, index, dp) {
if (index < 0) return 0;
if (index === 0 || index === 1) return stairs[index];
if (dp[index]) return dp[index];
dp[index] =
stairs[index] +
Math.min(
getMinCost(stairs, index - 1, dp),
getMinCost(stairs, index - 2, dp)
);
return dp[index];
}
function minCostClimbingStairs(cost) {
let dp = [];
let minCostFirst = getMinCost(cost, cost.length - 1, dp);
let minCostSecond = getMinCost(cost, cost.length - 2, dp);
return Math.min(minCostFirst, minCostSecond);
}
================================================
FILE: coding_interviews/leetcode/medium/min_operations/min_operations.py
================================================
def min_operations(n):
operations = 0
for index in range(n // 2):
operations += n - (2 * index + 1)
return operations
================================================
FILE: coding_interviews/leetcode/medium/min_pair_sum/min_pair_sum.py
================================================
# https://leetcode.com/problems/minimize-maximum-pair-sum-in-array
def min_pair_sum(nums):
sorted_nums = sorted(nums)
maximum_pair_sum = float('-Inf')
for i in range(len(nums) // 2):
pair_sum = sorted_nums[i] + sorted_nums[len(sorted_nums) - i - 1]
maximum_pair_sum = max(maximum_pair_sum, pair_sum)
return maximum_pair_sum
================================================
FILE: coding_interviews/leetcode/medium/min_partitions/min_partitions.py
================================================
# https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers
def min_partitions(n):
count = '0'
for digit_char in n:
if digit_char > count:
count = digit_char
return int(count)
def min_partitions(n):
return int(max(n))
================================================
FILE: coding_interviews/leetcode/medium/minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.js
================================================
/*
"(" => 1
")" => 1
"()" => 0
"(()" => 1
"())" => 1
"(((" => 3
")))" => 3
")(" => 2 => "()(" => "()()"
"()))((" => 4
*/
function minAddToMakeValid(s) {
let closeParenthesisCount = 0;
let openParenthesisStack = [];
for (let stringIndex = 0; stringIndex < s.length; stringIndex++) {
const char = s[stringIndex];
if (char === '(') {
openParenthesisStack.push(char);
} else {
if (openParenthesisStack.length) {
openParenthesisStack.pop();
} else {
closeParenthesisCount++;
}
}
}
return closeParenthesisCount + openParenthesisStack.length;
}
================================================
FILE: coding_interviews/leetcode/medium/minimum-amount-of-time-to-collect-garbage/minimum-amount-of-time-to-collect-garbage.js
================================================
function measure(garbage, travel, garbageType) {
let minutes = 0;
let lastGarbageItem = -1;
for (let [index, garbageItems] of garbage.entries()) {
let itemCount = 0;
for (let item of garbageItems) {
if (item === garbageType) {
lastGarbageItem = index;
itemCount++;
}
}
minutes += itemCount;
}
for (let index = 0; index < lastGarbageItem; index++) {
minutes += travel[index];
}
return minutes;
}
function garbageCollection(garbage, travel) {
let minutes = 0;
minutes += measure(garbage, travel, 'G');
minutes += measure(garbage, travel, 'M');
minutes += measure(garbage, travel, 'P');
return minutes;
}
================================================
FILE: coding_interviews/leetcode/medium/minimum-cost-of-buying-candies-with-discount/minimum-cost-of-buying-candies-with-discount.js
================================================
// https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount
function sum(cost) {
let sumOfAllCost = 0;
for (let c of cost) {
sumOfAllCost += c;
}
return sumOfAllCost;
}
function minimumCost(cost) {
if (cost.length <= 2) return sum(cost);
cost.sort((a, b) => a - b);
let allCost = 0;
let index;
for (index = cost.length - 1; index > 1; index -= 3) {
if (cost[index] <= cost[index - 2]) {
allCost += cost[index - 1] + cost[index - 2];
} else {
allCost += cost[index] + cost[index - 1];
}
}
allCost += sum(cost.slice(0, index + 1));
return allCost;
}
================================================
FILE: coding_interviews/leetcode/medium/minimum-number-of-steps-to-make-two-strings-anagram/README.md
================================================
# Minimum Number of Steps to Make Two Strings Anagram
[Problem link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram)
- Using the hash map data structure
- Runtime complexity: O(N), where N is the length of `s` and `t`
- Counting and comparing characters require hash maps to get the count based on each character
- key: characters
- value: count of each character
================================================
FILE: coding_interviews/leetcode/medium/minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.js
================================================
function buildMap(string) {
let map = new Map();
for (let char of string) {
if (map.has(char)) map.set(char, map.get(char) + 1);
else map.set(char, 1);
}
return map;
}
function minSteps(s, t) {
let sMap = buildMap(s);
let tMap = buildMap(t);
let minimumSteps = 0;
for (let [char, count] of sMap.entries()) {
if (!tMap.has(char)) {
minimumSteps += count;
} else if (count > tMap.get(char)) {
minimumSteps += count - tMap.get(char);
}
}
return minimumSteps;
}
================================================
FILE: coding_interviews/leetcode/medium/minimum_number_of_operations_to_move_all_balls_to_each_box/minimum_number_of_operations_to_move_all_balls_to_each_box.py
================================================
# https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/
def min_operations(boxes):
answer = []
for index in range(len(boxes)):
counter = 0
for box_index in range(len(boxes)):
if index != box_index and boxes[box_index] == '1':
counter += abs(index - box_index)
answer.append(counter)
return answer
def sum_moves(answer, boxes, boxes_indices):
moves, number_of_balls_seen = 0, 0
for index in boxes_indices:
answer[index] += moves
if boxes[index] == '1':
number_of_balls_seen += 1
moves += number_of_balls_seen
return answer
def min_operations(boxes):
length_boxes = len(boxes)
answer, moves, number_of_balls_seen = [0] * length_boxes, 0, 0
answer = sum_moves(answer, boxes, range(length_boxes))
return sum_moves(answer, boxes, reversed(range(length_boxes)))
================================================
FILE: coding_interviews/leetcode/medium/number-of-closed-islands/number-of-closed-islands.js
================================================
/**
- is it in the border: no closed island
- length == 1, 2: no closed island
- visited data structure: map
- iterate: [1,1] -> [n-1,n-1]
- is it 0
- go to top, bottom, left, right with a dfs fn
- is it 0: go to top, bottom, left, right with recursive call to the dfs fn
*/
function generateVisitedKey(row, col) {
return `${row}-${col}`;
}
function isInsideTheGrid(grid, row, col) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;
}
function dfs(grid, row, col, visited) {
let key = generateVisitedKey(row, col);
if (!isInsideTheGrid(grid, row, col)) {
return false;
}
if (grid[row][col] === 1 || visited[key]) {
return true;
}
if (grid[row][col] === 0 && !visited[key]) {
visited[key] = true;
let top = dfs(grid, row - 1, col, visited);
let bottom = dfs(grid, row + 1, col, visited);
let left = dfs(grid, row, col - 1, visited);
let right = dfs(grid, row, col + 1, visited);
return top && bottom && left && right;
}
}
function closedIsland(grid) {
if (grid.length <= 2 || grid[0].length <= 2) {
return 0;
}
let visited = {};
let closedIslandsNumber = 0;
for (let row = 1; row < grid.length - 1; row++) {
for (let col = 1; col < grid[row].length - 1; col++) {
let cell = grid[row][col];
let key = generateVisitedKey(row, col);
if (cell === 0 && !visited[key]) {
visited[key] = true;
let top = dfs(grid, row - 1, col, visited);
let bottom = dfs(grid, row + 1, col, visited);
let left = dfs(grid, row, col - 1, visited);
let right = dfs(grid, row, col + 1, visited);
let isClosedIsland = top && bottom && left && right;
if (isClosedIsland) {
closedIslandsNumber++;
}
}
}
}
return closedIslandsNumber;
}
================================================
FILE: coding_interviews/leetcode/medium/number-of-enclaves/number-of-enclaves.js
================================================
/**
- 0 => true
- dfs => (top, bottom, left, right)
- off the grid => false
*/
function getVisitedKey(row, col) {
return `${row}-${col}`;
}
function isOffTheGrid(grid, row, col) {
return row < 0 || col < 0 || row >= grid.length || col >= grid[0].length;
}
function dfs(grid, row, col, visited) {
if (isOffTheGrid(grid, row, col)) {
return -1;
}
if (grid[row][col] === 0) {
return 0;
}
let key = getVisitedKey(row, col);
if (visited[key]) {
return 0;
}
visited[key] = true;
let top = dfs(grid, row - 1, col, visited);
let bottom = dfs(grid, row + 1, col, visited);
let left = dfs(grid, row, col - 1, visited);
let right = dfs(grid, row, col + 1, visited);
return top === -1 || bottom === -1 || left === -1 || right === -1
? -1
: 1 + top + bottom + left + right;
}
function numEnclaves(grid) {
let numberOfLands = 0;
let visited = {};
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
let cell = grid[row][col];
let key = getVisitedKey(row, col);
if (cell && !visited[key]) {
visited[key] = true;
let top = dfs(grid, row - 1, col, visited);
let bottom = dfs(grid, row + 1, col, visited);
let left = dfs(grid, row, col - 1, visited);
let right = dfs(grid, row, col + 1, visited);
numberOfLands +=
top === -1 || bottom === -1 || left === -1 || right === -1
? 0
: 1 + top + bottom + left + right;
}
}
}
return numberOfLands;
}
================================================
FILE: coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js
================================================
function isInsideTheGrid(grid, row, col) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;
}
function dfs(grid, row, col) {
if (isInsideTheGrid(grid, row, col) && grid[row][col] === '1') {
grid[row][col] = 0; // marked as visited
dfs(grid, row - 1, col); // top
dfs(grid, row + 1, col); // bottom
dfs(grid, row, col - 1); // left
dfs(grid, row, col + 1); // right
}
}
function numIslands(grid) {
let numberOfIslands = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
if (grid[row][col] === '1') {
numberOfIslands++;
grid[row][col] = 0; // marked as visited
dfs(grid, row - 1, col); // top
dfs(grid, row + 1, col); // bottom
dfs(grid, row, col - 1); // left
dfs(grid, row, col + 1); // right
}
}
}
return numberOfIslands;
}
================================================
FILE: coding_interviews/leetcode/medium/number-of-laser-beams-in-a-bank/number-of-laser-beams-in-a-bank.js
================================================
/*
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.
There is one laser beam between any two security devices if both conditions are met:
The two devices are located on two different rows: r1 and r2, where r1 < r2.
- For each row i where r1 < i < r2, there are no security devices in the ith row.
- Laser beams are independent, i.e., one beam does not interfere nor join with another.
Return the total number of laser beams in the bank.
*/
export function numberOfBeams(bank) {
let lasersCount = 0;
const securityDevices = [];
for (let row = 0; row < bank.length; row++) {
let numberOfSecurityDevices = 0;
for (let col = 0; col < bank[row].length; col++) {
numberOfSecurityDevices += Number(bank[row][col]);
}
if (numberOfSecurityDevices) {
securityDevices.push(numberOfSecurityDevices);
}
}
for (let i = 0; i < securityDevices.length - 1; i++) {
lasersCount += securityDevices[i] * securityDevices[i + 1];
}
return lasersCount;
}
================================================
FILE: coding_interviews/leetcode/medium/number-of-laser-beams-in-a-bank/tests/number-of-laser-beams-in-a-bank.test.js
================================================
import { describe, expect, it } from 'vitest';
import { numberOfBeams } from '../number-of-laser-beams-in-a-bank';
describe('numberOfBeams', () => {
it('', () => {
expect(numberOfBeams(['011001', '000000', '010100', '001000'])).toEqual(8);
});
it('', () => {
expect(numberOfBeams(['000', '111', '000'])).toEqual(0);
});
});
================================================
FILE: coding_interviews/leetcode/medium/optimal-partition-of-string/optimal-partition-of-string.js
================================================
// https://leetcode.com/problems/optimal-partition-of-string
function partitionString(s) {
let partition = [];
let substring = '';
let substringMap = new Map();
for (let index = 0; index < s.length; index++) {
if (substringMap.has(s[index])) {
partition.push(substring);
substring = s[index];
substringMap = new Map([[s[index], 1]]);
} else {
substring += s[index];
substringMap.set(s[index], 1);
}
if (index === s.length - 1) {
partition.push(substring);
}
}
return partition.length;
}
================================================
FILE: coding_interviews/leetcode/medium/optimal-partition-of-string/optimized-optimal-partition-of-string.js
================================================
// https://leetcode.com/problems/optimal-partition-of-string
function partitionString(s) {
let substringMap = new Map([[s[0], 1]]);
let count = 1;
for (let index = 1; index < s.length; index++) {
if (substringMap.has(s[index])) {
substringMap = new Map([[s[index], 1]]);
count++;
} else {
substringMap.set(s[index], 1);
}
}
return count;
}
================================================
FILE: coding_interviews/leetcode/medium/pair-sum/pair-sum.js
================================================
/*
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
The twin sum is defined as the sum of a node and its twin.
Given the head of a linked list with even length, return the maximum twin sum of the linked list.
Input: head = [5,4,2,1]
Output: 6
Input: head = [4,2,2,3]
Output: 7
Input: head = [1,100000]
Output: 100001
*/
export function pairSum(list) {
let maximumTwin = 0;
for (let i = 0; i < Math.floor(list.length / 2); i++) {
maximumTwin = Math.max(maximumTwin, list[i] + list[list.length - 1 - i]);
}
return maximumTwin;
}
export function pairSumLinkedList(head) {
const list = [];
while (head) {
list.push(head.val);
head = head.next;
}
return pairSum(list);
}
================================================
FILE: coding_interviews/leetcode/medium/pair-sum/tests/pair-sum.test.js
================================================
import { describe, expect, it } from 'vitest';
import { pairSum } from '../pair-sum';
describe('pairSum', () => {
it('', () => {
expect(pairSum([5, 4, 2, 1])).toEqual(6);
});
it('', () => {
expect(pairSum([4, 2, 2, 3])).toEqual(7);
});
it('', () => {
expect(pairSum([1, 100000])).toEqual(100001);
});
});
================================================
FILE: coding_interviews/leetcode/medium/partition-array-according-to-given-pivot/partition-array-according-to-given-pivot.js
================================================
/*
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:
Every element less than pivot appears before every element greater than pivot.
Every element equal to pivot appears in between the elements less than and greater than pivot.
The relative order of the elements less than pivot and the elements greater than pivot is maintained.
More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.
Return nums after the rearrangement.
*/
export function pivotArray(nums, pivot) {
const lessThanPivot = [];
const equalToPivot = [];
const greaterThanPivot = [];
nums.forEach((num) => {
if (num === pivot) {
equalToPivot.push(num);
}
if (num < pivot) {
lessThanPivot.push(num);
}
if (num > pivot) {
greaterThanPivot.push(num);
}
});
return [...lessThanPivot, ...equalToPivot, ...greaterThanPivot];
}
================================================
FILE: coding_interviews/leetcode/medium/partition-array-according-to-given-pivot/tests/partition-array-according-to-given-pivot.test.js
================================================
import { describe, expect, it } from 'vitest';
import { pivotArray } from '../partition-array-according-to-given-pivot';
describe('pivotArray', () => {
it('', () => {
expect(pivotArray([9, 12, 5, 10, 14, 3, 10], 10)).toEqual([
9, 5, 3, 10, 10, 12, 14,
]);
});
it('', () => {
expect(pivotArray([-3, 4, 3, 2], 2)).toEqual([-3, 2, 4, 3]);
});
});
================================================
FILE: coding_interviews/leetcode/medium/permutation-in-string/permutation-in-string-sliding-window.js
================================================
function buildCharCount(string) {
let charCount = {};
for (let char of string) {
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
return charCount;
}
function isPermutation(possiblePermutation, string) {
let charCount = buildCharCount(string);
for (let char of possiblePermutation) {
if (charCount[char]) {
charCount[char]--;
} else {
return false;
}
}
return true;
}
function checkInclusion(s1, s2) {
for (let pointer1 = 0; pointer1 <= s2.length - s1.length; pointer1++) {
let pointer2 = pointer1 + s1.length;
let possiblePermutation = s2.substring(pointer1, pointer2);
if (isPermutation(possiblePermutation, s1)) {
return true;
}
}
return false;
}
================================================
FILE: coding_interviews/leetcode/medium/permutation-in-string/permutation-in-string.js
================================================
function buildCharCount(string) {
let charCount = {};
for (let char of string) {
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
return charCount;
}
function isPermutation(possiblePermutation, string) {
let charCount = buildCharCount(string);
for (let char of possiblePermutation) {
if (charCount[char]) {
charCount[char]--;
} else {
return false;
}
}
return true;
}
function checkInclusion(s1, s2) {
let char = s1[0];
let charIndices = [];
for (let index = 0; index < s2.length; index++) {
if (s2[index] === char) {
charIndices.push(index);
}
}
let possiblePermutations = [];
for (let index of charIndices) {
for (let pointer = 1; pointer <= s1.length; pointer++) {
let startIndex = index - s1.length + pointer;
let endIndex = index + pointer;
let substring = s2.substring(startIndex, endIndex);
if (substring.length === s1.length) {
possiblePermutations.push(substring);
}
}
}
for (let possiblePermutation of possiblePermutations) {
if (isPermutation(possiblePermutation, s1)) {
return true;
}
}
return false;
}
================================================
FILE: coding_interviews/leetcode/medium/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node-simpler.js
================================================
function dfs(node, next) {
if (!node) return;
node.next = next;
dfs(node.left, node.right);
dfs(node.right, next && next.left);
}
function connect(root) {
dfs(root, null);
return root;
}
================================================
FILE: coding_interviews/leetcode/medium/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.js
================================================
function connectHelperRight(node) {
if (!node) {
return;
}
connectHelper(node.left, node.right);
connectHelperRight(node.right);
}
function connectHelper(node, next) {
if (!node || !next) {
return;
}
node.next = next;
connectHelper(node.left, node.right);
connectHelper(node.right, next.left);
}
function connect(root) {
if (!root) {
return root;
}
connectHelper(root.left, root.right);
connectHelperRight(root.right);
return root;
}
================================================
FILE: coding_interviews/leetcode/medium/process_queries/process_queries.py
================================================
def process_queries(queries, m):
result = []
list_m = list(range(1, m + 1))
for index in range(len(queries)):
for index_m in range(len(list_m)):
if queries[index] == list_m[index_m]:
result.append(index_m)
list_m = [list_m[index_m]
] + list_m[:index_m] + list_m[index_m + 1:]
break
return result
================================================
FILE: coding_interviews/leetcode/medium/product-of-array-except-self/product-of-array-except-self.js
================================================
function productExceptSelf(nums) {
let zeros = 0;
let answer = [];
let product = 1;
for (let num of nums) {
if (num) product *= num;
else zeros++;
}
for (let num of nums) {
if (num) {
answer.push(zeros ? 0 : product / num);
} else {
answer.push(zeros > 1 ? 0 : product);
}
}
return answer;
}
================================================
FILE: coding_interviews/leetcode/medium/rearrange-array-elements-by-sign/rearrange-array-elements-by-sign.js
================================================
/*
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
You should rearrange the elements of nums such that the modified array follows the given conditions:
Every consecutive pair of integers have opposite signs.
For all integers with the same sign, the order in which they were present in nums is preserved.
The rearranged array begins with a positive integer.
Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
Example 1:
Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
Explanation:
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.
Example 2:
Input: nums = [-1,1]
Output: [1,-1]
Explanation:
1 is the only positive integer and -1 the only negative integer in nums.
So nums is rearranged to [1,-1].
*/
function isPositive(num) {
return num > 0;
}
export function rearrangeArray(nums) {
const negative = [];
const positive = [];
nums.forEach((num) => {
if (isPositive(num)) {
positive.push(num);
} else {
negative.push(num);
}
});
const rearrangeArray = [];
for (let i = 0; i < negative.length; i++) {
rearrangeArray.push(positive[i]);
rearrangeArray.push(negative[i]);
}
return rearrangeArray;
}
================================================
FILE: coding_interviews/leetcode/medium/rearrange-array-elements-by-sign/tests/rearrange-array-elements-by-sign.test.js
================================================
import { describe, expect, it } from 'vitest';
import { rearrangeArray } from '../rearrange-array-elements-by-sign';
describe('rearrangeArray', () => {
it('', () => {
expect(rearrangeArray([3, 1, -2, -5, 2, -4])).toEqual([
3, -2, 1, -5, 2, -4,
]);
});
it('', () => {
expect(rearrangeArray([-1, 1])).toEqual([1, -1]);
});
});
================================================
FILE: coding_interviews/leetcode/medium/reduce_array_size_to_the_half/reduce_array_size_to_the_half.py
================================================
# https://leetcode.com/problems/reduce-array-size-to-the-half
'''
Time Complexity: O(NlogN)
Space Complexity: O(N)
'''
def min_set_size(arr):
num_to_count, counts, min_size, current_length = {}, [], 0, len(arr)
for num in arr:
if num in num_to_count:
num_to_count[num] += 1
else:
num_to_count[num] = 1
for num in num_to_count:
counts.append(num_to_count[num])
counts = reversed(sorted(counts))
if len(arr) % 2 == 0:
cut = len(arr) / 2
else:
cut = len(arr + 1) / 2
for count in counts:
min_size += 1
current_length -= count
if current_length <= cut:
return min_size
return min_size
================================================
FILE: coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list-fast-slow.js
================================================
function removeNthFromEnd(head, n) {
fast = head;
slow = head;
while (n) {
fast = fast.next;
n--;
}
if (!fast) {
return head.next;
}
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
================================================
FILE: coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js
================================================
/**
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
function countNodes(head) {
let count = 0;
while (head) {
count++;
head = head.next;
}
return count;
}
function removeNthFromEnd(head, n) {
let count = countNodes(head);
let nth = count - n;
let node = head;
if (nth === 0) {
head = head.next;
return head;
}
while (node) {
if (nth === 1) {
node.next = node.next.next;
}
nth--;
node = node.next;
}
return head;
}
================================================
FILE: coding_interviews/leetcode/medium/rotate-array/rotate-array-optimized.js
================================================
function reverseInPlace(nums, start, end) {
while (start < end) {
let temporaryStart = nums[start];
nums[start] = nums[end];
nums[end] = temporaryStart;
start++;
end--;
}
}
function rotate(nums, k) {
if (k <= 0) {
return;
}
let start = 0;
let end = nums.length - 1;
let limit = k % nums.length;
reverseInPlace(nums, start, end - limit);
reverseInPlace(nums, end - limit + 1, end);
reverseInPlace(nums, start, end);
}
================================================
FILE: coding_interviews/leetcode/medium/rotate-array/rotate-array.js
================================================
function rotate(nums, k) {
let count = 0;
while (count < k) {
const num = nums.pop();
nums.unshift(num);
count++;
}
}
================================================
FILE: coding_interviews/leetcode/medium/rotate-image/rotate-image.js
================================================
function setupMatrix(matrix) {
const newMatrix = [];
for (let row = 0; row < matrix.length; row++) {
const newRow = [];
for (let col = 0; col < matrix[row].length; col++) {
newRow.push(matrix[row][col]);
}
newMatrix.push(newRow);
}
return newMatrix;
}
function rotateBorder(newMatrix, matrix, minRow, minCol, maxRow, maxCol) {
if (minRow >= maxRow && minCol >= maxCol) {
return;
}
// top
let row = minRow;
for (let col = minCol; col <= maxCol; col++) {
const value = newMatrix[minRow][col];
matrix[row][maxCol] = value;
row++;
}
// right
let col = maxCol;
for (let row = minRow; row <= maxRow; row++) {
const value = newMatrix[row][maxCol];
matrix[maxRow][col] = value;
col--;
}
// bottom
row = minRow;
for (let col = minCol; col <= maxCol; col++) {
const value = newMatrix[maxRow][col];
matrix[row][minCol] = value;
row++;
}
// left
col = maxCol;
for (let row = minRow; row <= maxRow; row++) {
const value = newMatrix[row][minCol];
matrix[minRow][col] = value;
col--;
}
rotateBorder(
newMatrix,
matrix,
minRow + 1,
minCol + 1,
maxRow - 1,
maxCol - 1
);
}
function rotate(matrix) {
const newMatrix = setupMatrix(matrix);
const minRow = 0;
const minCol = 0;
const maxRow = matrix.length - 1;
const maxCol = matrix[0].length - 1;
rotateBorder(newMatrix, matrix, minRow, minCol, maxRow, maxCol);
}
================================================
FILE: coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js
================================================
function getMiddle(start, end) {
return Math.floor((start + end) / 2);
}
function binarySearch(list, target) {
let start = 0;
let end = list.length - 1;
let middle = getMiddle(start, end);
while (start <= end) {
if (list[middle] === target) {
return true;
} else if (list[middle] > target) {
end = middle - 1;
middle = getMiddle(start, end);
} else {
start = middle + 1;
middle = getMiddle(start, end);
}
}
return false;
}
function searchMatrix(matrix, target) {
let targetRow;
for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {
let rowFirstNum = matrix[rowIndex][0];
let rowLastNum = matrix[rowIndex][matrix[rowIndex].length - 1];
if (target >= rowFirstNum && target <= rowLastNum) {
targetRow = rowIndex;
}
}
return matrix[targetRow] ? binarySearch(matrix[targetRow], target) : false;
}
================================================
FILE: coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.py
================================================
# https://leetcode.com/problems/search-a-2d-matrix
'''
Runtime Complexity: O(logNM)
Space Complexity: O(1)
'''
def search_matrix(matrix, target):
rows, columns = len(matrix), len(matrix[0])
start, end = 0, rows * columns - 1
while start <= end:
middle = (start + end) // 2
number = matrix[middle // columns][middle % columns]
if number == target:
return True
if target < number:
end = middle - 1
else:
start = middle + 1
return False
================================================
FILE: coding_interviews/leetcode/medium/search-a-2d-matrix-ii/search-a-2d-matrix-ii.py
================================================
# https://leetcode.com/problems/search-a-2d-matrix-ii
'''
Runtime Complexity: O(NlogM), where N is the number of rows and M is the number of columns
Space Complexity: O(1)
'''
def search_matrix(matrix, target):
for row in matrix:
if target_in_row(row, target):
return True
return False
def target_in_row(array, target):
start, end = 0, len(array) - 1
while start <= end:
middle = (start + end) // 2
number = array[middle]
if number == target:
return True
if number > target:
end = middle - 1
else:
start = middle + 1
return False
================================================
FILE: coding_interviews/leetcode/medium/set-matrix-zeroes/set-matrix-zeroes.js
================================================
function updateRow(matrix, row, visited) {
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col]) {
matrix[row][col] = 0;
visited[`${row}-${col}`] = true;
}
}
}
function updateCol(matrix, col, visited) {
for (let row = 0; row < matrix.length; row++) {
if (matrix[row][col]) {
matrix[row][col] = 0;
visited[`${row}-${col}`] = true;
}
}
}
function setZeroes(matrix) {
let visited = {};
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
let cell = matrix[row][col];
if (cell === 0 && !visited[`${row}-${col}`]) {
if (!visited[`row-${row}`]) {
updateRow(matrix, row, visited);
}
if (!visited[`col-${col}`]) {
updateCol(matrix, col, visited);
}
visited[`row-${row}`] = true;
visited[`col-${col}`] = true;
}
}
}
}
================================================
FILE: coding_interviews/leetcode/medium/sort-the-students-by-their-kth-score/sort-the-students-by-their-kth-score.js
================================================
function sortTheStudents(score, k) {
let column = [];
let sortedScores = [];
for (let row = 0; row < score.length; row++) {
column.push([row, score[row][k]]);
}
column.sort((pair1, pair2) => pair2[1] - pair1[1]);
for (let [row] of column) {
sortedScores.push(score[row]);
}
return sortedScores;
}
================================================
FILE: coding_interviews/leetcode/medium/sort_the_matrix_diagonally/sort_the_matrix_diagonally.py
================================================
def diagonal_sort(mat):
for column in range(len(mat[0]) - 1):
diagonal_list = []
col = column
for row in range(len(mat)):
diagonal_list.append(mat[row][col])
col += 1
if col >= len(mat[0]):
break
diagonal_list = sorted(diagonal_list)
col = column
for row in range(len(mat)):
mat[row][col] = diagonal_list[row]
col += 1
if col >= len(mat[0]):
break
for row in range(1, len(mat)):
diagonal_list = []
r = row
for column in range(len(mat[0])):
diagonal_list.append(mat[r][column])
r += 1
if r >= len(mat):
break
diagonal_list = sorted(diagonal_list)
r = row
for column in range(len(mat[0])):
mat[r][column] = diagonal_list[column]
r += 1
if r >= len(mat):
break
return mat
================================================
FILE: coding_interviews/leetcode/medium/string-compression/string-compression-copy.js
================================================
// https://leetcode.com/problems/string-compression
function compress(chars) {
let counter = 1;
let result = [];
for (let index = 0; index < chars.length - 1; index++) {
if (chars[index] === chars[index + 1]) counter++;
else {
result.push(chars[index]);
if (counter > 1) result.push(...counter.toString());
counter = 1;
}
if (index + 1 === chars.length - 1) {
result.push(chars[index + 1]);
if (counter > 1) result.push(...counter.toString());
}
}
return result.length;
}
================================================
FILE: coding_interviews/leetcode/medium/string-compression/string-compression.js
================================================
// https://leetcode.com/problems/string-compression
function compress(chars) {
let index = 0,
p1 = 0;
while (p1 < chars.length) {
let p2 = p1;
while (p2 < chars.length && chars[p1] === chars[p2]) {
p2++;
}
let count = p2 - p1;
chars[index++] = chars[p1];
if (count > 1) {
let countString = count.toString();
for (let char of countString) {
chars[index++] = char;
}
}
p1 = p2;
}
while (chars.length > index) {
chars.pop();
}
return chars.length;
}
================================================
FILE: coding_interviews/leetcode/medium/subrectangle_queries/subrectangle_queries.py
================================================
# https://leetcode.com/problems/subrectangle-queries
class SubrectangleQueries:
def __init__(self, rectangle):
self.rectangle = rectangle
def updateSubrectangle(self, row1, col1, row2, col2, newValue):
for row in range(row1, row2 + 1):
for col in range(col1, col2 + 1):
self.rectangle[row][col] = newValue
def getValue(self, row, col):
return self.rectangle[row][col]
================================================
FILE: coding_interviews/leetcode/medium/sum_of_nodes/sum_of_nodes.py
================================================
# https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent
'''
Given a binary tree, return the sum of values of nodes with even-valued grandparent.
(A grandparent of a node is the parent of its parent, if it exists.)
If there are no nodes with an even-valued grandparent, return 0.
'''
def sum_even_grandparent(node):
left = 0
right = 0
if node.left and node.left.left and node.val % 2 == 0:
left += node.left.left.val
if node.left and node.left.right and node.val % 2 == 0:
left += node.left.right.val
if node.left:
left += sum_even_grandparent(node.left)
if node.right and node.right.left and node.val % 2 == 0:
right += node.right.left.val
if node.right and node.right.right and node.val % 2 == 0:
right += node.right.right.val
if node.right:
right += sum_even_grandparent(node.right)
return right + left
def sum_even_grandparent_2(node):
return helper(node, 1, 1)
def helper(node, parent, grandparent):
if node is None:
return 0
return helper(node.left, node.val, parent) \
+ helper(node.right, node.val, parent) \
+ (node.val if grandparent % 2 == 0 else 0)
================================================
FILE: coding_interviews/leetcode/medium/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted-2.js
================================================
function twoSum(numbers, target) {
let start = 0;
let end = numbers.length - 1;
let result = [];
while (start < end) {
let sum = numbers[start] + numbers[end];
if (sum === target) {
result.push(start + 1);
result.push(end + 1);
break;
}
if (sum > target) end--;
else start++;
}
return result;
}
================================================
FILE: coding_interviews/leetcode/medium/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.js
================================================
function twoSum(numbers, target) {
let numberMap = {};
for (let index = 0; index < numbers.length; index++) {
let number = numbers[index];
numberMap[number] = index + 1;
}
let index1;
let index2;
for (let index = 0; index < numbers.length; index++) {
let remainder = target - numbers[index];
let remaindersIndex = numberMap[remainder];
if (remaindersIndex) {
index1 = index + 1;
index2 = remaindersIndex;
return [index1, index2];
}
}
}
================================================
FILE: coding_interviews/leetcode/medium/valid-sudoku/valid-sudoku.js
================================================
function isValidRow(board, row) {
let allNumbersInRow = new Set();
let countOfNumbersInRow = 0;
for (let index = 0; index <= 8; index++) {
let num = board[row][index];
if (num !== '.') {
allNumbersInRow.add(num);
countOfNumbersInRow++;
}
}
return allNumbersInRow.size === countOfNumbersInRow;
}
function isValidCol(board, col) {
let allNumbersInCol = new Set();
let countOfNumbersInCol = 0;
for (let index = 0; index <= 8; index++) {
let num = board[index][col];
if (num !== '.') {
allNumbersInCol.add(num);
countOfNumbersInCol++;
}
}
return allNumbersInCol.size === countOfNumbersInCol;
}
function isValidSquare(board, row, col) {
let allNumbersInSquare = new Set();
let countOfNumbersInSquare = 0;
for (let rowIndex = row; rowIndex <= row + 2; rowIndex++) {
for (let colIndex = col; colIndex <= col + 2; colIndex++) {
let num = board[rowIndex][colIndex];
if (num !== '.') {
allNumbersInSquare.add(num);
countOfNumbersInSquare++;
}
}
}
return allNumbersInSquare.size === countOfNumbersInSquare;
}
function isValidSudoku(board) {
let isValid = true;
for (let row = 0; row <= 8; row++) {
isValid = isValid && isValidRow(board, row);
}
for (let col = 0; col <= 8; col++) {
isValid = isValid && isValidCol(board, col);
}
for (let col = 0; col <= 6; col += 3) {
for (let row = 0; row <= 6; row += 3) {
isValid = isValid && isValidSquare(board, row, col);
}
}
return isValid;
}
================================================
FILE: coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-2.js
================================================
function isValidBST(node, min = -Infinity, max = Infinity) {
if (!node) return true;
if (node.val <= min || node.val >= max) return false;
return (
isValidBST(node.left, min, node.val) &&
isValidBST(node.right, node.val, max)
);
}
================================================
FILE: coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-almost-right.js
================================================
function isValidLeft(node, left) {
return node.val > left.val;
}
function isValidRight(node, right) {
return node.val < right.val;
}
function isValid(node, left, right) {
return isValidLeft(node, left) && isValidRight(node, right);
}
function compareNodeAndChildren(node, left, right) {
if (left && right) {
return (
isValid(node, left, right) &&
compareNodeAndChildren(left, left.left, left.right) &&
compareNodeAndChildren(right, right.left, right.right)
);
}
if (left) {
return (
isValidLeft(node, left) &&
compareNodeAndChildren(left, left.left, left.right)
);
}
if (right) {
return (
isValidRight(node, right) &&
compareNodeAndChildren(right, right.left, right.right)
);
}
return true;
}
function isValidBST(root) {
return compareNodeAndChildren(root, root.left, root.right);
}
================================================
FILE: coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree.js
================================================
function toList(node, treeList) {
if (!node) {
return;
}
treeList.push(node.val);
toList(node.left, treeList);
toList(node.right, treeList);
}
function dfs(node, value) {
if (!node) {
return new TreeNode(value);
}
if (value < node.val) {
node.left = dfs(node.left, value);
} else if (value > node.val) {
node.right = dfs(node.right, value);
}
return node;
}
function buildTree(treeList) {
let root = new TreeNode(treeList[0]);
for (let value of treeList.slice(1)) {
dfs(root, value);
}
return root;
}
function compareTrees(node1, node2) {
if (!node1 && !node2) {
return true;
}
if ((node1 && !node2) || (!node1 && node2)) {
return false;
}
return (
node1.val === node2.val &&
compareTrees(node1.left, node2.left) &&
compareTrees(node1.right, node2.right)
);
}
function isValidBST(root) {
let treeList = [];
toList(root, treeList);
let newTree = buildTree(treeList);
return compareTrees(root, newTree);
}
================================================
FILE: coding_interviews/leetcode/medium/watering-plants/tests/watering-plants.test.js
================================================
import { describe, expect, it } from 'vitest';
import { wateringPlants } from '../watering-plants';
describe('wateringPlants', () => {
it('', () => {
expect(wateringPlants([2, 2, 3, 3], 5)).toEqual(14);
});
it('', () => {
expect(wateringPlants([1, 1, 1, 4, 2, 3], 4)).toEqual(30);
});
it('', () => {
expect(wateringPlants([7, 7, 7, 7, 7, 7, 7], 8)).toEqual(49);
});
it('', () => {
expect(wateringPlants([2, 1], 2)).toEqual(4);
});
it('', () => {
expect(wateringPlants([3, 2, 4, 2, 1], 6)).toEqual(17);
});
});
================================================
FILE: coding_interviews/leetcode/medium/watering-plants/watering-plants.js
================================================
/*
You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.
Each plant needs a specific amount of water. You will water the plants in the following way:
Water the plants in order from left to right.
After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.
You cannot refill the watering can early.
You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.
Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.
Example 1:
Input: plants = [2,2,3,3], capacity = 5
Output: 14
Example 2:
Input: plants = [1,1,1,4,2,3], capacity = 4
Output: 30
Example 3:
Input: plants = [7,7,7,7,7,7,7], capacity = 8
Output: 49
*/
// [2, 2, 3, 3]
// capacity: 5 -> 3 -> 1
// steps: 1 -> 2 -> 4
export function wateringPlants(plants, capacity) {
let steps = 0;
const CAPACITY = capacity;
for (let i = 0; i < plants.length; i++) {
steps++;
capacity -= plants[i];
if (i < plants.length - 1 && capacity < plants[i + 1]) {
steps += i + 1;
steps += i + 1;
capacity = CAPACITY;
}
}
return steps;
}
================================================
FILE: coding_interviews/python/string.py
================================================
# length of a string
len('a string') # 8
# concatenate strings
s1 = 'string 1'
s2 = 'string 2'
s3 = s1 + s2 # 'string 1string 2'
# indexing
s1 = 'string 1'
s1[3] # 'i'
# slicing
s1 = 'string 1'
s1[:3] # 'str'
s1[2:] # 'ring 1'
# striping a string
s = ' a string '
s.strip() # 'a string'
# string in string
s1 = 'string 1'
s2 = 'string'
s3 = 'other'
s2 in s1 # True
s3 in s1 # False
================================================
FILE: coding_interviews/top-problems/are-anagrams.js
================================================
// Time Complexity: O(N) where N is the size of the string
// more precisely, it should be O(N1) + O(N2) where N1 = length of string1 and N2 = length of string2
// Space Complexity: O(N) where N is the size of the string
function hasDifferentLengths(string1, string2) {
return string1.length !== string2.length;
}
function buildCharsCount(string) {
let charactersCounter = {};
for (let char of string) {
if (charactersCounter[char]) {
charactersCounter[char]++;
} else {
charactersCounter[char] = 1;
}
}
return charactersCounter;
}
export function areAnagrams(string1, string2) {
if (hasDifferentLengths(string1, string2)) return false;
let charactersCounter1 = buildCharsCount(string1);
let charactersCounter2 = buildCharsCount(string2);
for (let char of Object.keys(charactersCounter1)) {
if (charactersCounter1[char] !== charactersCounter2[char]) {
return false;
}
}
return true;
}
================================================
FILE: coding_interviews/top-problems/first-and-last-index.js
================================================
/*
Given a sorted array of integers `arr` and an integer target,
find the index of the first and last position of target in `arr`.
In target can't be found in `arr`, return [-1, -1]
*/
// Runtime: O(N)
// Space: O(1)
export function firstAndLastIndex(list, target) {
let first = -1;
let last = -1;
for (let index = 0; index < list.length; index++) {
if (list[index] === target) {
first = index;
break;
}
}
for (let index = list.length; index >= 0; index--) {
if (list[index] === target) {
last = index;
break;
}
}
return [first, last];
}
// Runtime: O(logN)
// Space: O(1)
function getMiddle(start, end) {
return Math.floor((start + end) / 2);
}
function findIndex(list, target, type) {
let start = 0;
let end = list.length - 1;
let middle = getMiddle(start, end);
let index = -1;
while (start <= end) {
if (target > list[middle]) {
start = middle + 1;
middle = getMiddle(start, end);
}
if (target < list[middle]) {
end = middle - 1;
middle = getMiddle(start, end);
}
if (target === list[middle]) {
index = middle;
if (type === 'findFirst') {
end = middle - 1;
}
if (type === 'findLast') {
start = middle + 1;
}
middle = getMiddle(start, end);
}
}
return index;
}
function findFirstIndex(list, target) {
return findIndex(list, target, 'findFirst');
}
function findLastIndex(list, target) {
return findIndex(list, target, 'findLast');
}
export function firstAndLastIndexBinarySearch(list, target) {
return [findFirstIndex(list, target), findLastIndex(list, target)];
}
================================================
FILE: coding_interviews/top-problems/kth-largest.js
================================================
// Given an array of integers `arr` and an integer `k`, find the kth largest element
// Runtime: O(NlogN)
// Space: O(1)
export function kthLargest(list, k) {
return list.sort((num1, num2) => num1 - num2)[list.length - k];
}
================================================
FILE: coding_interviews/top-problems/min-sliding-window.js
================================================
function buildCharsCounter(s) {
let charsCounter = {};
for (let char of s) {
if (charsCounter[char]) {
charsCounter[char]++;
} else {
charsCounter[char] = 1;
}
}
return charsCounter;
}
function compare(s1, s2) {
let chars1 = buildCharsCounter(s1);
let chars2 = buildCharsCounter(s2);
for (let [char, counter] of Object.entries(chars1)) {
if (chars2[char] == undefined || chars2[char] > counter) {
return false;
}
}
return true;
}
function minSlidingWindow(s, t) {
for (let i = 0; i < s.length - t.length; i++) {
for (let j = i + t.length; j < s.length; j++) {
const substring = s.slice(i, j);
}
}
}
minSlidingWindow('adcfebeceabebadfcdfcbfcbead', 'abca');
================================================
FILE: coding_interviews/top-problems/tests/are-anagrams.test.js
================================================
import { describe, expect, it } from 'vitest';
import { areAnagrams } from '../are-anagrams';
describe('areAnagrams', () => {
it('', () => {
expect(areAnagrams('', '')).toBeTruthy();
});
it('', () => {
expect(areAnagrams('a', 'a')).toBeTruthy();
});
it('', () => {
expect(areAnagrams('bla', 'alb')).toBeTruthy();
});
it('', () => {
expect(areAnagrams('hahahehe', 'hehehaha')).toBeTruthy();
});
it('', () => {
expect(areAnagrams('a', 'b')).toBeFalsy();
});
it('', () => {
expect(areAnagrams('aa', 'a')).toBeFalsy();
});
it('', () => {
expect(areAnagrams('bla', 'elb')).toBeFalsy();
});
it('', () => {
expect(areAnagrams(' ', ' ')).toBeFalsy();
});
});
================================================
FILE: coding_interviews/top-problems/tests/first-and-last-index.test.js
================================================
import { describe, expect, it } from 'vitest';
import {
firstAndLastIndex,
firstAndLastIndexBinarySearch,
} from '../first-and-last-index';
describe('firstAndLastIndex', () => {
it('', () => {
expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 5)).toEqual([
5, 7,
]);
});
it('', () => {
expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 4)).toEqual([
4, 4,
]);
});
it('', () => {
expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 8, 9], 7)).toEqual([
-1, -1,
]);
});
});
describe('firstAndLastIndexBinarySearch', () => {
it('', () => {
expect(
firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 5)
).toEqual([5, 7]);
});
it('', () => {
expect(
firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 4)
).toEqual([4, 4]);
});
it('', () => {
expect(
firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 8, 9], 7)
).toEqual([-1, -1]);
});
});
================================================
FILE: coding_interviews/top-problems/tests/kth-largest.test.js
================================================
import { describe, expect, it } from 'vitest';
import { kthLargest } from '../kth-largest';
describe('kthLargest', () => {
it('', () => {
expect(kthLargest([4, 2, 9, 7, 5, 6, 7, 1, 3], 4)).toEqual(6);
});
});
================================================
FILE: college/graph/atoms.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
def plot_graph(graph, pos, title):
plt.figure(figsize=(6, 6))
nx.draw(graph, pos, with_labels=True, node_color='lightblue', node_size=2000, font_size=12, font_weight='bold', edge_color='gray')
plt.title(title)
plt.show()
# H₂O
# Adiciona vértices e conectas os átomos com arestas
# Define as posições de cada átomo
# Plota o grafo de água
water = nx.Graph()
water.add_nodes_from(['O', 'H1', 'H2'])
water.add_edges_from([('O', 'H1'), ('O', 'H2')])
water_pos = {'O': (0, 0), 'H1': (-1, -1), 'H2': (1, -1)}
plot_graph(water, water_pos, '(H2O)')
# CO₂
# Adiciona vértices e conectas os átomos com arestas
# Define as posições de cada átomo
# Plota o grafo de CO₂
co2 = nx.Graph()
co2.add_nodes_from(['C', 'O1', 'O2'])
co2.add_edges_from([('C', 'O1'), ('C', 'O2')])
co2_pos = {'C': (0, 0), 'O1': (-1, 0), 'O2': (1, 0)}
plot_graph(co2, co2_pos, '(CO2)')
================================================
FILE: college/web/css/estilos.css
================================================
body {
background-color: #f7f9ac;
}
h1 {
color: green;
text-align: center;
}
p.corpoDoTexto {
color: blue;
}
p.corpoDoTexto2 {
color: red;
}
================================================
FILE: college/web/css/index.html
================================================
CSS
Título título título
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
================================================
FILE: college/web/index.html
================================================
Título da página
Título Principal - H1
Sub-título H2
Sub-título H3
Sub-título H4
Sub-título H5
Sub-título H6
Testando o parágrafo
================================================
FILE: college/web/js.js
================================================
Math.max(1, 2); // 2
Math.min(1, 2); // 1
Math.pow(2, 2); // 4
Math.sqrt(4); // 2
================================================
FILE: college/web/loop.js
================================================
let matrix = [];
for (let row = 1; row <= 4; row++) {
let nums = [];
let num = row + 1;
for (let col = 1; col <= 5; col++) {
nums.push(num);
num += row + 1;
}
matrix.push(nums);
}
console.log(matrix);
================================================
FILE: competitive-programming/4clojure/problem01.clj
================================================
; http://www.4clojure.com/problem/1
(= true true)
================================================
FILE: competitive-programming/4clojure/problem02.clj
================================================
; http://www.4clojure.com/problem/2
(= (- 10 (* 2 3)) 4)
================================================
FILE: competitive-programming/4clojure/problem03.clj
================================================
; http://www.4clojure.com/problem/3#prob-title
(= "HELLO WORLD" (.toUpperCase "hello world"))
================================================
FILE: competitive-programming/4clojure/problem04.clj
================================================
;; http://www.4clojure.com/problem/4
(= (list :a :b :c) '(:a :b :c))
================================================
FILE: competitive-programming/4clojure/problem05.clj
================================================
;; http://www.4clojure.com/problem/5#prob-title
(= '(1 2 3 4) (conj '(2 3 4) 1))
(= '(1 2 3 4) (conj '(3 4) 2 1))
================================================
FILE: competitive-programming/4clojure/problem06.clj
================================================
;; http://www.4clojure.com/problem/6
(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))
================================================
FILE: competitive-programming/4clojure/problem07.clj
================================================
;; http://www.4clojure.com/problem/7
(= [1 2 3 4] (conj [1 2 3] 4))
(= [1 2 3 4] (conj [1 2] 3 4))
================================================
FILE: competitive-programming/4clojure/problem19.clj
================================================
; http://www.4clojure.com/problem/19
; Solution 1
(fn [coll]
(loop [item (first coll)
coll coll]
(if (empty? (rest coll))
item
(recur (first (rest coll)) (rest coll)))))
; Solution 2
(fn [coll]
(first (reverse coll)))
; Solution 3
#(first (reverse %))
; Solution 4
(comp first reverse)
; Solution 5
(fn [coll]
(-> coll
reverse
first))
; Solution 6
(fn [coll]
(loop [[item & remaining] coll]
(if (empty? remaining)
item
(recur remaining))))
================================================
FILE: competitive-programming/4clojure/problem20.clj
================================================
; http://www.4clojure.com/problem/20
(comp second reverse)
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/armstrong.cpp
================================================
#include
#include
#include
#include
#include
using namespace std;
int main()
{
long int n;
scanf("%li", &n);
vector vetor;
while (n != 0) {
int total = 0, temp = n, teste, result=0;
while (temp != 0) {
teste = temp % 10;
vetor.push_back(teste);
temp = temp / 10;
}
for (int i = 2; i < 10; i++) {
total = 0;
for (int j = 0; j < vetor.size(); j++) {
total += pow(vetor[j], i);
}
if (total == n) {
result = i;
break;
}
}
if (result)
cout << result << endl;
else
cout << "N" << endl;
scanf("%li", &n);
vetor.clear();
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/calculadora.cpp
================================================
#include
#include
using namespace std;
int main()
{
int ip1[4];
int ip2[4];
int mas[4];
while (scanf("%i.%i.%i.%i %i.%i.%i.%i %i.%i.%i.%i", &ip1[0],&ip1[1],&ip1[2],&ip1[3],&ip2[0],&ip2[1],&ip2[2],&ip2[3],&mas[0],&mas[1],&mas[2],&mas[3]) != -1) {
int r = 1;
int i = 0;
for (i = 0; i < 4; i++)
{
if ((ip1[i] & mas[i]) != (ip2[i] & mas[i]))
r = 0;
}
if (r)
cout << "S" << endl;
else
cout << "N" << endl;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/cartoes.cpp
================================================
#include
#include
using namespace std;
int is_alberto_turn(int counter) {
if (counter % 2 == 0)
return 1;
return 0;
}
int main() {
int n, temp;
vector v, vetor_a;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> temp;
v.push_back(temp);
}
for (int i = 0; i < n; i++) {
if (is_alberto_turn(i)) {
if (v[0] > v.back()) {
vetor_a.push_back(v[0]);
v.erase(v.begin());
} else {
vetor_a.push_back(v.back());
v.pop_back();
}
} else if (v.size() > 1) {
if (v[0] > v.back())
v.erase(v.begin());
else
v.pop_back();
}
}
int total = 0;
for (int i = 0; i < n; i++)
total += vetor_a[i];
cout << total << endl;
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/concurso.cpp
================================================
#include
#include
#include
using namespace std;
int main() {
int n, l, c, result;
string conto;
while (scanf("%d %d %d", &n, &l, &c) != EOF) {
cin.ignore();
getline(cin, conto);
if (conto.size() == (l * c)) result = 1;
else result = (conto.size() / (l * c)) + 1;
cout << result << endl;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/coral.cpp
================================================
#include
#include
#include
#include
#include
using namespace std;
bool is_integer(float k) {
return std::floor(k) == k;
}
bool all_equal(vector &vetorzin) {
sort(vetorzin.begin(), vetorzin.end());
return (vetorzin[0] == vetorzin.back());
}
int main() {
int n, temp;
float total=0;
vector v;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> temp;
total += temp;
v.push_back(temp);
}
if (is_integer(total / n))
cout << -1 << endl;
else {
if (all_equal(v))
cout << 1 << endl;
else {
// algorithm to know how many times
}
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/elevador.cpp
================================================
#include
#include
#include
#include
#include
using namespace std;
bool has_four(string number) {
for (int i = 0; i < number.length(); i++)
if (number[i] == '4') return true;
return false;
}
bool has_thirteen(string number) {
for (int i = 0; i < number.length()-1; i++)
if (number[i] == '1' && number[i+1] == '3') return true;
return false;
}
int main () {
int n, total=0;
while (scanf("%d", &n) != EOF) {
ostringstream converter;
converter << n;
string number = converter.str();
for (int i = 0; i < n; i++) {
if (has_four(number) || has_thirteen(number)) total++;
cout << total << endl;
}
cout << n + total << endl;
total = 0;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/estacionamento.cpp
================================================
#include
#include
using namespace std;
int main() {
int v, p, result=0;
cin >> v >> p;
while (v + p != 0) {
vector v1;
vector< vector > v2;
while (p--) {
int he, me, hs, ms, found=0;
cin >> he >> me >> hs >> ms;
v1.push_back(he);
v1.push_back(me);
v1.push_back(hs);
v1.push_back(ms);
if (v > 0) {
v2.push_back(v1);
v--;
} else {
for (int i = 0; i < v2.size(); i++) {
if (v1[0] > v2[i][2] || (v1[0] == v2[i][2] && v1[1] > v2[i][3])) {
v2.push_back(v1);
found = 1;
break;
}
}
if (!found) result++;
}
v1.clear();
}
cout << result << endl;
cin >> v >> p;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/extenso.cpp
================================================
#include
#include
#include
#include
using namespace std;
// stringstream ss;
// string num1;
// ss << n1[0];
// ss >> num1;
void split(string &n1, string &n2, string number) {
int dot_index = number.find(".");
n1 = number.substr(0, dot_index);
n2 = number.substr(dot_index+1, number.size()-1);
}
string transformNumberToCents(string cents) {
string result="";
string ar[] = { "DEZ", "ONZE", "DOZE", "TREZE", "QUATORZE", "QUINZE", "DEZESSEIS", "DEZESSETE", "DEZOITO", "DEZENOVE" };
string um_a_nove[] = { "UM", "DOIS", "TRES", "QUATRO", "CINCO", "SEIS", "SETE", "OITO", "NOVE" };
vector values(ar, ar + sizeof(ar)/sizeof(ar[0]));
vector sec_values(um_a_nove, um_a_nove + sizeof(um_a_nove)/sizeof(um_a_nove[0]));
stringstream ss;
string num1;
ss << cents[0];
ss >> num1;
int cent_unit = stoi(num1);
if (cents[0] == '0') result += sec_values[cent_unit-1];
else if (cents[0] == '1') result += values[cent_unit];
else if (cents[0] == '2') result += "VINTE E " + sec_values[cent_unit-1];
else if (cents[0] == '3') result += "TRINTA E " + sec_values[cent_unit-1];
else if (cents[0] == '4') result += "QUARENTA E " + sec_values[cent_unit-1];
else if (cents[0] == '5') result += "CINQUENTA E " + sec_values[cent_unit-1];
else if (cents[0] == '6') result += "SESSENTA E " + sec_values[cent_unit-1];
else if (cents[0] == '7') result += "SETENTA E " + sec_values[cent_unit-1];
else if (cents[0] == '8') result += "OITENTA E " + sec_values[cent_unit-1];
else if (cents[0] == '9') result += "NOVENTA E " + sec_values[cent_unit-1];
return result;
}
string transformNumberToReal(string reais) {
string result="";
string um_a_nove[] = { "UM", "DOIS", "TRES", "QUATRO", "CINCO", "SEIS", "SETE", "OITO", "NOVE" };
vector sec_values(um_a_nove, um_a_nove + sizeof(um_a_nove)/sizeof(um_a_nove[0]));
string ar[] = { "DEZ", "ONZE", "DOZE", "TREZE", "QUATORZE", "QUINZE", "DEZESSEIS", "DEZESSETE", "DEZOITO", "DEZENOVE" };
vector values(ar, ar + sizeof(ar)/sizeof(ar[0]));
string dez_a_noventa[] = { "VINTE", "TRINTA", "QUARENTA", "CINQUENTA", "SESSENTA", "SETENTA", "OITENTA", "NOVENTA" };
vector dicker(dez_a_noventa, dez_a_noventa + sizeof(dez_a_noventa)/sizeof(dez_a_noventa[0]));
string cem_a_novecentos[] = { "CENTO", "DUZENTOS", "TREZENTOS", "QUATROCENTOS", "QUINHENTOS", "SEICENTOS", "SETECENTOS", "OITOCENTOS", "NOVECENTOS" };
vector hundred(cem_a_novecentos, cem_a_novecentos + sizeof(cem_a_novecentos)/sizeof(cem_a_novecentos[0]));
if (reais.size() == 1) {
result += sec_values[stoi(reais)-1];
} else if (reais.size() == 2) {
stringstream ss; string n1, n2;
ss << reais[0]; ss >> n1;
ss << reais[1]; ss >> n2;
if (reais[0] == '1') {
result += values[stoi(n2)];
} else {
result += dicker[stoi(n1)-1] + " E " + sec_values[stoi(n2)-1];
}
} else if (reais.size() == 3) {
stringstream ss; string n1, n2, n3;
ss << reais[0]; ss >> n1;
ss << reais[1]; ss >> n2;
ss << reais[2]; ss >> n3;
result += hundred[stoi(n1)-1] + " E " + dicker[stoi(n2)-1] + " E " + sec_values[stoi(n3)-1];
} else if (reais.size() == 4){
stringstream ss; string n1, n2, n3, n4;
ss << reais[0]; ss >> n1;
ss << reais[1]; ss >> n2;
ss << reais[2]; ss >> n3;
ss << reais[3]; ss >> n4;
result += sec_values[stoi(n1)-1] + " MIL E " + hundred[stoi(n2)-1] + " E " + dicker[stoi(n3)-1] + " E " + sec_values[stoi(n4)-1];
} else if (reais.size() == 5) {
stringstream ss; string n1, n2, n3, n4, n5;
ss << reais[0]; ss >> n1;
ss << reais[1]; ss >> n2;
ss << reais[2]; ss >> n3;
ss << reais[3]; ss >> n4;
ss << reais[4]; ss >> n5;
if (reais[0] == '1') {
result += values[stoi(n2)] + " MIL E " + hundred[stoi(n3)-1] + " E " + dicker[stoi(n4)-1] + " E " + sec_values[stoi(n5)-1];
} else {
result += dicker[stoi(n1)-1] + " E " + sec_values[stoi(n2)-1]; + " MIL E " + hundred[stoi(n3)-1] + " E " + dicker[stoi(n4)-1] + " E " + sec_values[stoi(n5)-1];
}
} else if (reais.size() == 6) {
stringstream ss; string n1, n2, n3, n4, n5, n6;
ss << reais[0]; ss >> n1;
ss << reais[1]; ss >> n2;
ss << reais[2]; ss >> n3;
ss << reais[3]; ss >> n4;
ss << reais[4]; ss >> n5;
ss << reais[5]; ss >> n6;
result += hundred[stoi(n1)-1] + " E " + dicker[stoi(n2)-1] + " E " + sec_values[stoi(n3)-1] + " MIL E" + hundred[stoi(n4)-1] + " E " + dicker[stoi(n5)-1] + " E " + sec_values[stoi(n6)-1];
} else {
result += "UM MILHAO";
}
return result;
}
int main() {
string number;
cin >> number;
while(number != "0.00") {
string n1, n2, result="";
split(n1, n2, number);
n1 = transformNumberToReal(n1);
n2 = transformNumberToCents(n2);
if (n1 == "0") {
if (n2 == "01")
result += n2 + " CENTAVO";
else
result += n2 + " CENTAVOS";
} else if (n1 == "1") {
if (n2 == "00")
result += n1 + " REAL";
else if (n2 == "01")
result += n1 + " REAL E " + n2 + " CENTAVO";
else
result += n1 + " REAL E " + n2 + " CENTAVOS";
} else {
if (n2 == "00")
result += n1 + " REAIS";
else if (n2 == "01")
result += n1 + " REAIS E " + n2 + " CENTAVO";
else
result += n1 + " REAIS E " + n2 + " CENTAVOS";
}
cout << result;
cin >> number;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/goldbach.cpp
================================================
#include
#include
#include
using namespace std;
int verifica_primo(int n) {
int total_divisivel = 0;
if (n == 2) {
return 1;
}
if ((n % 2) == 0)
return 0;
int s = sqrt(n);
for (int i = 3; i <= s; i += 2) {
if (n % i == 0){
return 0;
}
}
return 1;
}
int main()
{
int n, n1, n2;
scanf("%i", &n);
while (n != 0) {
if (n % 2 != 0)
cout << "erro" << endl;
else {
for (int i = 2; i <= n; i++) {
if (verifica_primo(i)) {
n1 = i;
if (verifica_primo(n-n1)) {
n2 = n - n1;
break;
}
}
}
cout << n1 << " " << n2 << endl;
}
scanf("%i", &n);
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/matriz_esparsa.cpp
================================================
#include
using namespace std;
int main() {
int n, x, total, zeros, medium;
cin >> n;
while (n--) {
cin >> x;
total = x * x;
zeros = total - (3 * x - 2);
medium = total / 2;
if (zeros > medium) cout << "S " << zeros << endl;
else cout << "N " << zeros << endl;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/pascal.cpp
================================================
#include
using namespace std;
int triangulo_pascal(int n, int m) {
if ((m == 0 || n == 0) || (m == 1 && n == 1) || (m == n))
return 1;
return triangulo_pascal(n - 1, m) + triangulo_pascal(n - 1, m - 1);
}
int main() {
int n, x, y;
cin >> n;
while (n--) {
cin >> x;
cin >> y;
cout << triangulo_pascal(x, y) << endl;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/polinomio.cpp
================================================
#include
#include
#include
#include
#include
using namespace std;
int solvePartEquation(string part_equation, int value) {
int result, inicio=0, constante, expo;
int x = part_equation.find("x");
stringstream ss1; ss1 << part_equation.substr(0, x); ss1 >> constante;
stringstream ss2; ss2 << part_equation.substr(x+1, part_equation.size()-x); ss2 >> expo;
result = constante * (pow(value, expo));
return result;
}
int main() {
int n, time=1, i_inicio=0, total;
string temp;
vector vetor_de_valores, vetor_de_variaveis, vetor_de_sinais;
vector vetor_de_resultados;
cin >> n;
while (n--) {
string equacao;
int number_of_values;
cin >> equacao;
cin >> number_of_values;
for (int i = 0; i < number_of_values; i++){
cin >> temp;
vetor_de_valores.push_back(temp);
}
for (int i = 0; i < equacao.size(); i++) {
if (equacao[i] == '+' || equacao[i] == '-') {
vetor_de_variaveis.push_back(equacao.substr(i_inicio, i-i_inicio));
vetor_de_sinais.push_back(equacao.substr(i, 1));
i_inicio = i+1;
}
}
for (int i = 0; i < vetor_de_valores.size(); i++) {
int valor;
stringstream ss; ss << vetor_de_valores[i]; ss >> valor;
total = solvePartEquation(vetor_de_variaveis[0], valor);
for (int j = 1; j < vetor_de_variaveis.size(); j++){
if (vetor_de_sinais[j-1] == "+")
total += solvePartEquation(vetor_de_variaveis[j], valor);
else
total -= solvePartEquation(vetor_de_variaveis[j], valor);
vetor_de_resultados.push_back(total);
}
}
cout << "Caso " << time << ": ";
for (int i = 0; vetor_de_resultados.size(); i++)
cout << vetor_de_resultados[i] << " ";
cout << endl;
time++;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/quadrado.cpp
================================================
#include
#include
#include
using namespace std;
int main() {
int n;
vector v;
cin >> n;
while (n--) {
int temp;
for (int i = 0; i < 4; i++) {
cin >> temp;
v.push_back(temp);
}
sort(v);
if (v[0] == v[1] && v[0] == v[2] && v[0] == v[3]) cout << "quadrado" << endl;
else if (v[0] == v[1] && v[2] == v[3]) cout << "retangulo" << endl;
else if (v[0] + v[1] + v[2] > v[3]) cout << "quadrilatero" << endl;
else cout << "invalido" << endl;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2011/vagas.cpp
================================================
#include
using namespace std;
int main() {
int c, total;
cin >> c;
while (c != -1) {
total = (c - 6) / 5;
cout << total << endl;
cin >> c;
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2017_1/A.cpp
================================================
#include
using namespace std;
#define MAX_SIZE (1 << 20)
int segtree[MAX_SIZE];
int lazy[MAX_SIZE];
void build_segtree(int A[], int node, int start, int end) {
if (start == end) {
segtree[node] = A[start];
} else {
int middle = (start + end) / 2;
build_segtree(A, node * 2, start, middle);
build_segtree(A, node * 2 + 1, middle + 1, end);
}
}
void propagate(int p, int start, int end) {
if (lazy[p] != 0) {
segtree[p] += lazy[p];
if (start != end) {
lazy[p * 2] += lazy[p];
lazy[p * 2 + 1] += lazy[p];
}
lazy[p] = 0;
}
}
void lazy_update(int p, int start, int end, int left, int right, int inc) {
propagate(p, start, end);
if (start > end || end < left || start > right) return; // Totally out of range
if (start >= left && end <= right) { // Totally in the range
segtree[p] += inc;
if (start != end) { // Not a leaf
lazy[p * 2] += inc;
lazy[p * 2 + 1] += inc;
}
return;
}
// Partially in the range
int middle = (start + end) / 2;
lazy_update(p * 2, start, middle, left, right, inc);
lazy_update(p * 2 + 1, middle + 1, end, left, right, inc);
}
int lazy_query(int p, int start, int end, int left, int right) {
if (start > end || left > end || right < start) return -1;
propagate(p, start, end);
if (start >= left && end <= right) return segtree[p];
int middle = (end + start) / 2;
int left_f = lazy_query(p * 2, start, middle, left, right);
int right_f = lazy_query(p * 2 + 1, middle + 1, end, left, right);
}
void print_all_leaves(int p, int start, int end) {
if (start > end) return;
propagate(p, start, end);
if (start == end) cout << segtree[p] << endl;
int middle = (start + end) / 2;
print_all_leaves(p * 2, start, middle);
print_all_leaves(p * 2 + 1, middle + 1, end);
}
int main() {
int N, C, left, right, most_frequent;
cin >> N >> C;
int A[N];
for (int i = 0; i < N; i++) A[i] = 1;
build_segtree(A, 1, 0, N - 1);
while (C--) {
cin >> left >> right;
most_frequent = lazy_query(1, 0, N - 1, left, right);
lazy_update(1, 0, N - 1, left, right, most_frequent);
}
//print_all_leaves(1, 0, N - 1);
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2017_2/D.cpp
================================================
#include
using namespace std;
bool is_prime(int N) {
return true;
}
int main() {
int N;
cin >> N;
if (is_prime(N)) {
cout << 0 << endl;
} else {
}
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2017_2/F.cpp
================================================
#include
#include
#include
using namespace std;
int main() {
int N, M, num;
vector V;
cin >> N >> M;
while (N--) {
cin >> num;
V.push_back(num);
}
sort(V.begin(), V.end(), greater());
int result = M;
for (int i = M; i < V.size(); i++) {
if (V[i] == V[i-1]) result++;
else break;
}
cout << result << endl;
return 0;
}
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2017_2/J.py
================================================
n = input()
print n % 3
================================================
FILE: competitive-programming/acm-icpc-br/regionals_2017_2/M.cpp
================================================
#include
using namespace std;
int main() {
int N1, N2, N3;
cin >> N1 >> N2 >> N3;
int one = N2 * 2 + N3 * 4,
two = N1 * 2 + N3 * 2,
three = N1 * 4 + N2 * 2;
if (one <= two && one <= three) cout << one << endl;
else if (two <= three) cout << two << endl;
else cout << three << endl;
return 0;
}
================================================
FILE: competitive-programming/codeforces/div2/black_square.cpp
================================================
// http://codeforces.com/problemset/problem/828/B
#include
#include
#include
using namespace std;
int main() {
int N, M, black = 0,
smaller_black_x = 101,
smaller_black_y = 101,
bigger_black_x = -1,
bigger_black_y = -1,
result_square,
bigger_side;
vector matrix;
string line;
cin >> N >> M;
cin.ignore();
for (int i = 0; i < N; i++) {
getline(cin, line);
matrix.push_back(line);
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (matrix[i][j] == 'B') {
if (i < smaller_black_y) smaller_black_y = i;
if (i > bigger_black_y) bigger_black_y = i;
if (j < smaller_black_x) smaller_black_x = j;
if (j > bigger_black_x) bigger_black_x = j;
black++;
}
}
}
if (black == 0) {
cout << 1 << endl;
return 0;
}
bigger_side = max(bigger_black_x - smaller_black_x + 1, bigger_black_y - smaller_black_y + 1);
if (bigger_side > N || bigger_side > M) cout << -1 << endl;
else cout << bigger_side * bigger_side - black << endl;
return 0;
}
================================================
FILE: competitive-programming/codeforces/div2/karen_and_morning.cpp
================================================
// http://codeforces.com/contest/816/problem/A
#include
#include
using namespace std;
int to_digit(char c) {
return c - '0';
}
int main() {
string hour;
cin >> hour;
int hour_decimal = to_digit(hour[0]),
hour_unit = to_digit(hour[1]),
minute_decimal = to_digit(hour[3]),
minute_unit = to_digit(hour[4]),
hour_int, minute;
hour_int = hour_decimal * 10 + hour_unit;
minute = minute_decimal * 10 + minute_unit;
if (hour_int == minute_unit * 10 + minute_decimal) cout << 0 << endl;
else if (hour_int == 1 && minute < 10) cout << 10 - minute << endl;
else if ((hour_int == 0 ||hour_int == 1 || hour_int == 2 || hour_int == 3 || hour_int == 4 || hour_int == 5 ||
hour_int == 10 || hour_int == 11 || hour_int == 12 || hour_int == 13 || hour_int == 14 || hour_int == 15 ||
hour_int == 20 || hour_int == 21 || hour_int == 22 || hour_int == 23)
&& minute > 10) cout << 70 - minute << endl;
else if ((hour_int == 0 ||hour_int == 1 || hour_int == 2 || hour_int == 3 || hour_int == 4 ||
hour_int == 10 || hour_int == 11 || hour_int == 12 || hour_int == 13 || hour_int == 14 ||
hour_int == 20 || hour_int == 21 || hour_int == 22 || hour_int == 23)
&& minute > 10)
return 0;
}
================================================
FILE: competitive-programming/codeforces/div2/keyboard_layouts.cpp
================================================
// http://codeforces.com/problemset/problem/831/B
#include
#include
using namespace std;
bool is_uppercase(char word) {
string original_alphabet = "ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz";
return original_alphabet.find(word) < 26;
}
char build_new_word(char letter, string alpha1, string alpha2) {
string original_alphabet = "ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz", numbers = "0123456789";
if (numbers.find(letter) >= 0 && numbers.find(letter) <= 9)
return letter;
else if (is_uppercase(letter)) {
char l = original_alphabet[original_alphabet.find(letter) + 26];
int index = alpha1.find(l);
char new_l = alpha2[index];
return original_alphabet[original_alphabet.find(new_l) - 26];
}
return alpha2[alpha1.find(letter)];
}
int main() {
string alpha1, alpha2, word, result;
cin >> alpha1 >> alpha2 >> word;
for (int i = 0; i < word.size(); i++) {
result += build_new_word(word[i], alpha1, alpha2);
}
cout << result << endl;
return 0;
}
================================================
FILE: competitive-programming/codeforces/div2/the_child_and_the_homework.cpp
================================================
// http://codeforces.com/contest/437/problem/A
#include
using namespace std;
string solve(string a, string b, string c, string d) {
bool a_smaller = (a.size()-2 <= (b.size()-2) / 2) && (a.size()-2 <= (c.size()-2) / 2) && (a.size()-2 <= (d.size()-2) / 2),
a_bigger = (a.size()-2 >= (b.size()-2) * 2) && (a.size()-2 >= (c.size()-2) * 2) && (a.size()-2 >= (d.size()-2) * 2),
b_smaller = (b.size()-2 <= (a.size()-2) / 2) && (b.size()-2 <= (c.size()-2) / 2) && (b.size()-2 <= (d.size()-2) / 2),
b_bigger = (b.size()-2 >= (a.size()-2) * 2) && (b.size()-2 >= (c.size()-2) * 2) && (b.size()-2 >= (d.size()-2) * 2),
c_smaller = (c.size()-2 <= (a.size()-2) / 2) && (c.size()-2 <= (b.size()-2) / 2) && (c.size()-2 <= (d.size()-2) / 2),
c_bigger = (c.size()-2 >= (a.size()-2) * 2) && (c.size()-2 >= (b.size()-2) * 2) && (c.size()-2 >= (d.size()-2) * 2),
d_smaller = (d.size()-2 <= (a.size()-2) / 2) && (d.size()-2 <= (b.size()-2) / 2) && (d.size()-2 <= (c.size()-2) / 2),
d_bigger = (d.size()-2 >= (b.size()-2) * 2) && (d.size()-2 >= (a.size()-2) * 2) && (d.size()-2 >= (c.size()-2) * 2);
vector great_choices;
if (a_bigger || a_smaller) great_choices.push_back("A");
if (b_bigger || b_smaller) great_choices.push_back("B");
if (c_bigger || c_smaller) great_choices.push_back("C");
if (d_bigger || d_smaller) great_choices.push_back("D");
if (great_choices.size() == 1) return great_choices[0];
return "C";
}
int main() {
string a, b, c, d;
cin >> a >> b >> c >> d;
cout << solve(a, b, c, d) << endl;
return 0;
}
================================================
FILE: competitive-programming/codeforces/div2/the_child_and_toy.cpp
================================================
// http://codeforces.com/contest/437/problem/C
#include
using namespace std;
int min(int x, int y, int values[]) {
return values[x-1] < values[y-1] ? values[x-1] : values[y-1];
}
int main() {
int n, m, x, y, value, min_energy = 0;
cin >> n >> m;
int values[n];
for (int i = 0; i < n; i++) {
cin >> value;
values[i] = value;
}
while (m--) {
cin >> x >> y;
min_energy += min(x, y, values);
}
cout << min_energy << endl;
return 0;
}
================================================
FILE: competitive-programming/codeforces/div2/valera_and_plates.cpp
================================================
// http://codeforces.com/problemset/problem/369/A
#include
using namespace std;
int main() {
int N, M, K, num, W = 0;
cin >> N >> M >> K;
while (N--) {
cin >> num;
if (num == 1) {
if (M == 0) W++;
else M--;
} else {
if (K == 0) {
if (M == 0) W++;
else M--;
} else {
K--;
}
}
}
cout << W << endl;
return 0;
}
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/.exercism/metadata.json
================================================
{"track":"clojure","exercise":"armstrong-numbers","id":"c708010a47824f9daeddb51af2f51b2f","url":"https://exercism.io/my/solutions/c708010a47824f9daeddb51af2f51b2f","handle":"LeandroTk","is_requester":true,"auto_approve":false}
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/.lein-failures
================================================
{}
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/.lein-repl-history
================================================
(defn int->digits [int]
(map (comp #(- % 48) int) (str int)))
(defn power-by-two [digits]
(map #(* % (count digits)) digits))
(defn powered-sum [num]
(->> num
int->digits
power-by-two
(reduce +)))
(defn armstrong? [num]
(= (powered-sum num) num))
(armstrong? 123)
(int->digits 123)
quit
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/README.md
================================================
# Armstrong Numbers
An [Armstrong number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number that is the sum of its own digits each raised to the power of the number of digits.
For example:
- 9 is an Armstrong number, because `9 = 9^1 = 9`
- 10 is *not* an Armstrong number, because `10 != 1^2 + 0^2 = 1`
- 153 is an Armstrong number, because: `153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153`
- 154 is *not* an Armstrong number, because: `154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190`
Write some code to determine whether a number is an Armstrong number.
## Source
Wikipedia [https://en.wikipedia.org/wiki/Narcissistic_number](https://en.wikipedia.org/wiki/Narcissistic_number)
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/project.clj
================================================
(defproject armstrong-numbers "0.1.0-SNAPSHOT"
:description "armstrong-numbers exercise"
:url "https://github.com/exercism/clojure/tree/master/exercises/armstrong-numbers"
:dependencies [[org.clojure/clojure "1.10.0"]])
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/src/armstrong_numbers.clj
================================================
(ns armstrong-numbers)
(defn int->digits [num]
(map (comp #(- % 48) int) (str num)))
(defn power-by-two [digits digit]
(reduce * (repeat (count digits) digit)))
(defn power-all-by-two [digits]
(map (partial power-by-two digits) digits))
(defn powered-sum [num]
(->> num
int->digits
power-all-by-two
(reduce +)))
(defn armstrong? [num]
(= (powered-sum num) num))
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/target/classes/META-INF/maven/armstrong-numbers/armstrong-numbers/pom.properties
================================================
#Leiningen
#Thu Jan 31 22:57:53 BRST 2019
groupId=armstrong-numbers
artifactId=armstrong-numbers
version=0.1.0-SNAPSHOT
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/target/stale/leiningen.core.classpath.extract-native-dependencies
================================================
[{:dependencies {org.clojure/clojure {:vsn "1.10.0", :native-prefix nil}, org.clojure/spec.alpha {:vsn "0.2.176", :native-prefix nil}, org.clojure/core.specs.alpha {:vsn "0.2.44", :native-prefix nil}, nrepl {:vsn "0.5.3", :native-prefix nil}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil}, clojure-complete {:vsn "0.2.5", :native-prefix nil}}, :native-path "target/native"} {:native-path "target/native", :dependencies {org.clojure/clojure {:vsn "1.10.0", :native-prefix nil, :native? false}, org.clojure/spec.alpha {:vsn "0.2.176", :native-prefix nil, :native? false}, org.clojure/core.specs.alpha {:vsn "0.2.44", :native-prefix nil, :native? false}, nrepl {:vsn "0.5.3", :native-prefix nil, :native? false}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil, :native? false}, clojure-complete {:vsn "0.2.5", :native-prefix nil, :native? false}}}]
================================================
FILE: competitive-programming/exercism/clojure/armstrong-numbers/test/armstrong_numbers_test.clj
================================================
(ns armstrong-numbers-test
(:require [clojure.test :refer [deftest is testing]]
[armstrong-numbers :refer [armstrong?]]))
(deftest armstrong-number-5
(testing "Single digit numbers are Armstrong numbers"
(is (armstrong? 5))))
(deftest not-armstrong-number-10
(testing "There are no 2 digit Armstrong numbers"
(is (not (armstrong? 10)))))
(deftest armstrong-number-153
(testing "Three digit number that is an Armstrong number"
(is (armstrong? 153))))
(deftest not-armstrong-number-100
(testing "Three digit number that is not an Armstrong number"
(is (not (armstrong? 100)))))
(deftest armstrong-number-9474
(testing "Four digit number that is an Armstrong number"
(is (armstrong? 9474))))
(deftest not-armstrong-number-9475
(testing "Four digit number that is not an Armstrong number"
(is (not (armstrong? 9476)))))
(deftest armstrong-number-9926315
(testing "Seven digit number that is an Armstrong number"
(is (armstrong? 9926315))))
(deftest not-armstrong-number-9926314
(testing "Seven digit number that is not an Armstrong number"
(is (not (armstrong? 9926314)))))
(deftest armstrong-number-21897142587612075
(testing "Seventeen digit number that is an Armstrong number"
(is (armstrong? 21897142587612075))))
================================================
FILE: competitive-programming/exercism/clojure/hello-world/README.md
================================================
# Hello World
The classical introductory exercise. Just say "Hello, World!".
["Hello, World!"](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) is
the traditional first program for beginning programming in a new language
or environment.
The objectives are simple:
- Write a function that returns the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
### Project Structure
Clojure exercises in exercism use [leiningen](http://leiningen.org/) to configure and run your code
and use [leiningen standard directory structure](https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md#directory-layout).
You will find a test file named `hello_world_test.clj` inside `test` directory.
Write your code in `src/hello_world.clj`. It should use the namespace `hello-world` so that tests can pick it up.
### Running tests
Run the tests using `lein test` command and make them pass:
```
$ lein test
lein test hello-world-test
Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
```
Then submit the exercise using:
```
$ exercism submit src/hello_world.clj
```
For more detailed instructions and learning resources refer [exercism's clojure language page](http://exercism.io/languages/clojure).
## Source
This is an exercise to introduce users to using Exercism [http://en.wikipedia.org/wiki/%22Hello,_world!%22_program](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program)
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
================================================
FILE: competitive-programming/exercism/clojure/hello-world/project.clj
================================================
(defproject hello-world "0.1.0-SNAPSHOT"
:description "hello-world exercise."
:url "https://github.com/exercism/clojure/tree/master/exercises/hello-world"
:dependencies [[org.clojure/clojure "1.9.0"]])
================================================
FILE: competitive-programming/exercism/clojure/hello-world/src/hello-world.clj
================================================
(ns hello-world)
(defn hello [] "Hello, World!")
================================================
FILE: competitive-programming/exercism/clojure/hello-world/test/hello-world-test.clj
================================================
(ns hello-world-test
(:require [clojure.test :refer [deftest is]]
hello-world))
(deftest hello-world-test
(is (= "Hello, World!" (hello-world/hello))))
================================================
FILE: competitive-programming/exercism/clojure/two-fer/.exercism/metadata.json
================================================
{"track":"clojure","exercise":"two-fer","id":"13de8e46adaa41d68299dc2b4a20ff1c","url":"https://exercism.io/my/solutions/13de8e46adaa41d68299dc2b4a20ff1c","handle":"LeandroTk","is_requester":true,"auto_approve":false}
================================================
FILE: competitive-programming/exercism/clojure/two-fer/.lein-failures
================================================
{}
================================================
FILE: competitive-programming/exercism/clojure/two-fer/.nrepl-port
================================================
62204
================================================
FILE: competitive-programming/exercism/clojure/two-fer/README.md
================================================
# Two Fer
`Two-fer` or `2-fer` is short for two for one. One for you and one for me.
Given a name, return a string with the message:
```text
One for X, one for me.
```
Where X is the given name.
However, if the name is missing, return the string:
```text
One for you, one for me.
```
Here are some examples:
|Name | String to return
|:------:|:-----------------:
|Alice | One for Alice, one for me.
|Bob | One for Bob, one for me.
| | One for you, one for me.
|Zaphod | One for Zaphod, one for me.
## Source
[https://github.com/exercism/problem-specifications/issues/757](https://github.com/exercism/problem-specifications/issues/757)
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
================================================
FILE: competitive-programming/exercism/clojure/two-fer/project.clj
================================================
(defproject two-fer "0.1.0-SNAPSHOT"
:description "two-fer exercise."
:url "https://github.com/exercism/clojure/tree/master/exercises/two-fer"
:dependencies [[org.clojure/clojure "1.8.0"]])
================================================
FILE: competitive-programming/exercism/clojure/two-fer/src/two_fer.clj
================================================
(ns two-fer)
(defn two-fer
([] "One for you, one for me.")
([name] (str "One for " name ", one for me.")))
================================================
FILE: competitive-programming/exercism/clojure/two-fer/target/classes/META-INF/maven/two-fer/two-fer/pom.properties
================================================
#Leiningen
#Sun Feb 03 05:19:15 BRST 2019
groupId=two-fer
artifactId=two-fer
version=0.1.0-SNAPSHOT
================================================
FILE: competitive-programming/exercism/clojure/two-fer/target/repl-port
================================================
62204
================================================
FILE: competitive-programming/exercism/clojure/two-fer/target/stale/leiningen.core.classpath.extract-native-dependencies
================================================
[{:dependencies {org.clojure/clojure {:vsn "1.8.0", :native-prefix nil}, nrepl {:vsn "0.5.3", :native-prefix nil}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil}, clojure-complete {:vsn "0.2.5", :native-prefix nil}}, :native-path "target/native"} {:native-path "target/native", :dependencies {org.clojure/clojure {:vsn "1.8.0", :native-prefix nil, :native? false}, clojure-complete {:vsn "0.2.5", :native-prefix nil, :native? false}, nrepl {:vsn "0.5.3", :native-prefix nil, :native? false}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil, :native? false}}}]
================================================
FILE: competitive-programming/exercism/clojure/two-fer/test/two_fer_test.clj
================================================
(ns two-fer-test
(:require [clojure.test :refer [deftest is]]
two-fer))
(deftest two-fer-test
(is (= "One for you, one for me." (two-fer/two-fer))))
(deftest name-alice-test
(is (= "One for Alice, one for me." (two-fer/two-fer "Alice"))))
(deftest name-bob-test
(is (= "One for Bob, one for me." (two-fer/two-fer "Bob"))))
================================================
FILE: competitive-programming/exercism/javascript/allergies.js
================================================
export class Allergies {
constructor(score) {
this.score = score;
this.scores = [128, 64, 32, 16, 8, 4, 2, 1];
this.scoreToFoodMapper = {
1: 'eggs',
2: 'peanuts',
4: 'shellfish',
8: 'strawberries',
16: 'tomatoes',
32: 'chocolate',
64: 'pollen',
128: 'cats',
};
}
list() {
this.listOfFoods = [];
this.findMaxSmallerThanScore(this.score);
return [...new Set(this.listOfFoods)];
}
findMaxSmallerThanScore(score) {
if (score === 0) return;
const maxSmallerThanScore = this.scores.find(
(currentScore) => currentScore <= score
);
this.listOfFoods.unshift(this.scoreToFoodMapper[maxSmallerThanScore]);
score -= maxSmallerThanScore;
return this.findMaxSmallerThanScore(score);
}
allergicTo(food) {
return this.list().includes(food);
}
}
================================================
FILE: competitive-programming/exercism/javascript/collatz-conjecture.js
================================================
export const steps = n => {
if (n <= 0) throw "Only positive numbers are allowed";
let times = 0;
while (n !== 1) {
if (n % 2 === 0) {
n /= 2;
} else {
n = n * 3 + 1;
}
times++;
}
return times;
};
================================================
FILE: competitive-programming/exercism/javascript/count-words.js
================================================
const SPECIAL_CHARACTERS = /[!@#\$%\^\&*\".,;:?<>~`(\){}[\]\\/\+=_-]/g;
const SPACE_CHARACTERS = /\s+/g;
function isEmptySpace(string) {
return string !== '';
}
function removeOpenQuote(word) {
return word.startsWith("'") ? word.substring(1) : word;
}
function removeCloseQuote(word) {
return word.endsWith("'") ? word.substring(0, word.length - 1) : word;
}
function removeQuotes(word) {
return removeCloseQuote(removeOpenQuote(word));
}
export const countWords = (phrase) => {
const words = phrase
.toLowerCase()
.replaceAll(SPECIAL_CHARACTERS, ' ')
.split(SPACE_CHARACTERS)
.filter(isEmptySpace)
.map(removeQuotes);
const wordCounter = {};
for (const word of words) {
wordCounter[word] = (wordCounter[word] || 0) + 1;
}
return wordCounter;
};
================================================
FILE: competitive-programming/exercism/javascript/etl.js
================================================
export const transform = (scoreToLetters) => {
const obj = {};
Object.entries(scoreToLetters).forEach(([score, letters]) => {
letters.forEach((letter) => {
obj[letter.toLowerCase()] = Number(score);
});
});
return obj;
};
================================================
FILE: competitive-programming/exercism/javascript/flatten-array.js
================================================
export const flatten = (list) => {
const result = [];
list.forEach((item) => {
if (Array.isArray(item)) {
result.push(...flatten(item));
} else if (item !== undefined && item !== null) {
result.push(item);
}
});
return result;
};
================================================
FILE: competitive-programming/exercism/javascript/gigasecond.js
================================================
const year = date => date.getUTCFullYear();
const month = date => date.getUTCMonth();
const day = date => date.getUTCDate() + 11574;
const hours = date => date.getUTCHours() + 1;
const minutes = date => date.getUTCMinutes() + 46;
const second = date => date.getUTCSeconds() + 40;
export const gigasecond = date =>
new Date(
Date.UTC(
year(date),
month(date),
day(date),
hours(date),
minutes(date),
second(date)
)
);
================================================
FILE: competitive-programming/exercism/javascript/hello-world.js
================================================
export const hello = () => "Hello, World!";
================================================
FILE: competitive-programming/exercism/javascript/leap.js
================================================
// https://exercism.io/tracks/javascript/exercises/leap/solutions/0e7bcf1db4974d159ab9ebe9e961bcd1
export const isLeap = year =>
(year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
================================================
FILE: competitive-programming/exercism/javascript/perfect-numbers.js
================================================
const getAllDivisibleNumbers = (number) => {
const divisibleNumbers = [];
for (let i = 1; i <= number / 2; i++) {
if (number % i === 0) {
divisibleNumbers.push(i);
}
}
return divisibleNumbers;
};
const sumAllNumbers = (numbers) =>
numbers.reduce((sum, number) => sum + number, 0);
export const classify = (number) => {
if (number <= 0) {
throw new Error('Classification is only possible for natural numbers.');
}
const divisibleNumbers = getAllDivisibleNumbers(number);
const sumOfNumbers = sumAllNumbers(divisibleNumbers);
console.log('divisibleNumbers', divisibleNumbers);
console.log('sumOfNumbers', sumOfNumbers);
if (sumOfNumbers === number) {
return 'perfect';
}
if (sumOfNumbers > number) {
return 'abundant';
}
if (sumOfNumbers < number) {
return 'deficient';
}
};
================================================
FILE: competitive-programming/exercism/javascript/phone-number.js
================================================
const isDigit = (char) => '0' <= char && char <= '9';
const getDigits = (phoneNumber) =>
phoneNumber.split('').filter(isDigit).join('');
const verifyDigitsLength = (digits) => {
if (digits.length < 10) {
throw new Error('Incorrect number of digits');
}
if (digits.length >= 12) {
throw new Error('More than 11 digits');
}
};
const verifyCountryCode = (digits) => {
if (digits.length === 11 && digits[0] !== '1') {
throw new Error('11 digits must start with 1');
}
};
const verifyAreaCode = (digits) => {
if (digits.length === 10 && digits[0] === '0') {
throw new Error('Area code cannot start with zero');
}
if (digits.length === 10 && digits[0] === '1') {
throw new Error('Area code cannot start with one');
}
if (digits.length === 11 && digits[1] === '0') {
throw new Error('Area code cannot start with zero');
}
if (digits.length === 11 && digits[1] === '1') {
throw new Error('Area code cannot start with one');
}
};
const verifyExchangeCode = (digits) => {
if (digits.length === 10 && digits[3] === '0') {
throw new Error('Exchange code cannot start with zero');
}
if (digits.length === 10 && digits[3] === '1') {
throw new Error('Exchange code cannot start with one');
}
if (digits.length === 11 && digits[4] === '0') {
throw new Error('Exchange code cannot start with zero');
}
if (digits.length === 11 && digits[4] === '1') {
throw new Error('Exchange code cannot start with one');
}
};
const verifyAlphabetChars = (digits) => {
const alphabetChars = digits.match(/[A-Za-z]/g);
if (alphabetChars && alphabetChars.length) {
throw new Error('Letters not permitted');
}
};
const verifyPunctuationChars = (digits) => {
const punctuationChars = digits.match(/[,\/#!$%\^&\*;:{}=\_`~]/g);
if (punctuationChars && punctuationChars.length) {
throw new Error('Punctuations not permitted');
}
};
export const clean = (phoneNumber) => {
const digits = getDigits(phoneNumber);
verifyAlphabetChars(phoneNumber);
verifyPunctuationChars(phoneNumber);
verifyDigitsLength(digits);
verifyCountryCode(digits);
verifyAreaCode(digits);
verifyExchangeCode(digits);
return digits.length === 11 ? digits.substring(1) : digits;
};
================================================
FILE: competitive-programming/exercism/javascript/resistor-color.js
================================================
const colorCode = color => COLORS.indexOf(color);
const COLORS = [
"black",
"brown",
"red",
"orange",
"yellow",
"green",
"blue",
"violet",
"grey",
"white"
];
export { colorCode, COLORS };
================================================
FILE: competitive-programming/exercism/javascript/resistor-colors.js
================================================
// https://exercism.io/my/solutions/0a95e6a8ebb94efeac42b2c6e065818b
const COLORS = [
"black",
"brown",
"red",
"orange",
"yellow",
"green",
"blue",
"violet",
"grey",
"white"
];
const reducer = (acc, resistanceValue) => acc + resistanceValue;
const resistanceValuesString = (resistorsColors) =>
resistorsColors
.map((color) => COLORS.indexOf(color))
.reduce(reducer, "");
export const value = (resistorsColors) => {
return Number(resistanceValuesString(resistorsColors));
};
================================================
FILE: competitive-programming/exercism/javascript/reverse-string.js
================================================
const lastChar = str => str[str.length - 1];
export const reverseString = str => {
if (str.length <= 1) {
return str;
}
return lastChar(str) + reverseString(str.substring(0, str.length - 1));
};
================================================
FILE: competitive-programming/exercism/javascript/sublist.js
================================================
const COMPARISON = {
EQUAL: 'EQUAL',
SUBLIST: 'SUBLIST',
SUPERLIST: 'SUPERLIST',
UNEQUAL: 'UNEQUAL',
};
export class List {
constructor(numbers = []) {
this.numbers = numbers;
}
compare(otherList) {
const otherNumbers = otherList.numbers;
const numbersLength = this.numbers.length;
const otherLength = otherNumbers.length;
if (numbersLength < otherLength) {
return this.isSublist(otherNumbers)
? COMPARISON.SUBLIST
: COMPARISON.UNEQUAL;
}
if (numbersLength > otherLength) {
return this.isSuperList(this.numbers, otherNumbers)
? COMPARISON.SUPERLIST
: COMPARISON.UNEQUAL;
}
return this.isIdentical(this.numbers, otherNumbers)
? COMPARISON.EQUAL
: COMPARISON.UNEQUAL;
}
isIdentical(numbers, otherList) {
if (numbers.length !== otherList.length) return false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] !== otherList[i]) return false;
}
return true;
}
isSublist(otherNumbers) {
const numbersLength = this.numbers.length;
const otherLength = otherNumbers.length;
for (let i = 0; i < otherLength - numbersLength + 1; i++) {
if (
this.isIdentical(this.numbers, otherNumbers.slice(i, i + numbersLength))
) {
return true;
}
}
return false;
}
isSuperList(numbers, otherNumbers) {
const numbersLength = numbers.length;
const otherLength = otherNumbers.length;
for (let i = 0; i < numbersLength - otherLength + 1; i++) {
if (this.isIdentical(numbers.slice(i, i + otherLength), otherNumbers)) {
return true;
}
}
return false;
}
}
================================================
FILE: competitive-programming/exercism/javascript/sum-of-multiples.js
================================================
export const sum = (multiples, limit) => {
let sum = 0;
let counted = {};
multiples.forEach((multiple) => {
if (!multiple) return;
let increment = multiple;
while (increment < limit) {
if (!counted[increment]) sum += increment;
counted[increment] = true;
increment += multiple;
}
});
return sum;
};
================================================
FILE: competitive-programming/exercism/javascript/triangle.js
================================================
export function Triangle(side1, side2, side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
Triangle.prototype.isEquilateral = function() {
return this.side1 == this.side2 && this.side1 == this.side3;
};
Triangle.prototype.isIsosceles = function() {
return (
this.side1 == this.side2 ||
this.side1 == this.side3 ||
this.side2 == this.side3
);
};
Triangle.prototype.anyNonPositiveSide = function() {
return this.side1 <= 0 || this.side2 <= 0 || this.side3 <= 0;
};
Triangle.prototype.isInequality = function() {
return (
this.side1 > this.side2 + this.side3 ||
this.side2 > this.side1 + this.side3 ||
this.side3 > this.side2 + this.side1
);
};
Triangle.prototype.kind = function() {
if (this.anyNonPositiveSide() || this.isInequality()) {
throw "Not a triangle";
} else if (this.isEquilateral()) {
return "equilateral";
} else if (this.isIsosceles()) {
return "isosceles";
} else {
return "scalene";
}
};
================================================
FILE: competitive-programming/exercism/javascript/two-fer.js
================================================
export const twoFer = (name = "you") => `One for ${name}, one for me.`;
================================================
FILE: competitive-programming/hacker-rank/algorithms/strings/palindrome_index.py
================================================
# https://www.hackerrank.com/challenges/palindrome-index
import sys
def is_palindrome(s):
return s == s[::-1]
def palindrome_index(s):
for i in range(len(s)):
if is_palindrome(s[i+1:len(s)-i]):
return i
if is_palindrome(s[i:len(s)-i-1]):
return len(s)-i-1
q = int(raw_input().strip())
for num in range(q):
s = raw_input().strip()
result = palindrome_index(s)
print(result)
================================================
FILE: competitive-programming/hacker-rank/algorithms/warmup/birthday_cake_candles.py
================================================
# https://www.hackerrank.com/challenges/birthday-cake-candles/problem
def birthday_cake_candles(n, ar):
sorted_ar = sorted(ar, reverse = True)
tallest = sorted_ar[0]
result = 0
for candle_height in sorted_ar:
if tallest == candle_height:
result += 1
return result
print(birthday_cake_candles(int(raw_input()), map(int, raw_input().strip().split(' '))))
================================================
FILE: competitive-programming/hacker-rank/algorithms/warmup/mini_max_sum.py
================================================
def mini_max_sum(arr):
sorted_arr = sorted(arr)
print sum(sorted_arr[0:4]), sum(sorted_arr[1:5])
if __name__ == "__main__":
arr = map(int, raw_input().strip().split(' '))
mini_max_sum(arr)
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/angry_professor.cpp
================================================
#include
using namespace std;
int main() {
int t, n, k, time, total_students_arrived_before_class=0;
cin >> t;
while (t--) {
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> time;
if (time <= 0) total_students_arrived_before_class++;
}
if (total_students_arrived_before_class >= k) cout << "NO" << endl;
else cout << "YES" << endl;
total_students_arrived_before_class=0;
}
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/arrays_introduction.cpp
================================================
// https://www.hackerrank.com/challenges/arrays-introduction?h_r=next-challenge&h_v=zen
#include
#include
using namespace std;
int main() {
vector v;
int n, x;
cin >> n;
while (n--) {
cin >> x;
v.push_back(x);
}
for (int i = v.size()-1; i >= 0; i--) cout << v[i] << " ";
cout << endl;
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/diagonal_difference.cpp
================================================
#include
#include
using namespace std;
int main() {
vector< vector > matrix;
vector v;
int n, diag1=0, diag2=0, temp;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> temp;
v.push_back(temp);
}
matrix.push_back(v);
v.clear();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) diag1 += matrix[i][j];
if (j == n - 1 - i) diag2 += matrix[i][j];
}
}
int result = diag1 - diag2;
if (result < 0) result *= -1;
cout << result << endl;
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/input_and_output.cpp
================================================
// https://www.hackerrank.com/challenges/cpp-input-and-output
#include
#include
#include
#include
#include
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
cout << a + b + c << endl;
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/library_fine.cpp
================================================
#include
using namespace std;
int main() {
int day1, day2, month1, month2, year1, year2;
cin >> day1 >> month1 >> year1;
cin >> day2 >> month2 >> year2;
if (year1 == year2) {
if (month1 == month2) {
if (day1 <= day2)
cout << 0 << endl;
else
cout << 15 * (day1 - day2) << endl;
} else if (month1 > month2) {
cout << 500 * (month1 - month2) << endl;
} else {
cout << 0 << endl;
}
} else if (year1 > year2) {
cout << 10000 * (year1 - year2) << endl;
} else {
cout << 0 << endl;
}
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/plus_minus.cpp
================================================
#include
using namespace std;
int main() {
int n, temp, num, zeros=0, positives=0, negatives=0;
cin >> n;
temp = n;
while (temp--) {
cin >> num;
if (num > 0) positives++;
else if (num < 0) negatives++;
else zeros++;
}
double divisor = n;
cout << positives / divisor << endl;
cout << negatives / divisor << endl;
cout << zeros / divisor << endl;
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/staircase.cpp
================================================
#include
#include
using namespace std;
int main() {
int n;
string result="";
cin >> n;
int total = n;
while (n) {
for (int i = 1; i < n; i++)
result += " ";
int num_symbol = total + 1 - n;
for (int i = 0; i < num_symbol; i++) {
result += "#";
}
cout << result << endl;
result.clear();
n--;
}
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/time_conversion.cpp
================================================
#include
#include
using namespace std;
int main() {
string time;
cin >> time;
char letter = time[8];
if (letter == 'A'){
if (time.substr(0, 2) == "12") cout << "00" + time.substr(2, 6);
else if (time.substr(0, 2) == "13") cout << "01" + time.substr(2, 6);
else if (time.substr(0, 2) == "14") cout << "02" + time.substr(2, 6);
else if (time.substr(0, 2) == "15") cout << "03" + time.substr(2, 6);
else if (time.substr(0, 2) == "16") cout << "04" + time.substr(2, 6);
else if (time.substr(0, 2) == "17") cout << "05" + time.substr(2, 6);
else if (time.substr(0, 2) == "18") cout << "06" + time.substr(2, 6);
else if (time.substr(0, 2) == "19") cout << "07" + time.substr(2, 6);
else if (time.substr(0, 2) == "20") cout << "08" + time.substr(2, 6);
else if (time.substr(0, 2) == "21") cout << "09" + time.substr(2, 6);
else if (time.substr(0, 2) == "22") cout << "10" + time.substr(2, 6);
else if (time.substr(0, 2) == "23") cout << "" + time.substr(2, 6);
else cout << time.substr(0, 8);
} else {
if (time.substr(0, 2) == "00") cout << "24" + time.substr(2, 6);
else if (time.substr(0, 2) == "01") cout << "13" + time.substr(2, 6);
else if (time.substr(0, 2) == "02") cout << "14" + time.substr(2, 6);
else if (time.substr(0, 2) == "03") cout << "15" + time.substr(2, 6);
else if (time.substr(0, 2) == "04") cout << "16" + time.substr(2, 6);
else if (time.substr(0, 2) == "05") cout << "17" + time.substr(2, 6);
else if (time.substr(0, 2) == "06") cout << "18" + time.substr(2, 6);
else if (time.substr(0, 2) == "07") cout << "19" + time.substr(2, 6);
else if (time.substr(0, 2) == "08") cout << "20" + time.substr(2, 6);
else if (time.substr(0, 2) == "09") cout << "21" + time.substr(2, 6);
else if (time.substr(0, 2) == "10") cout << "22" + time.substr(2, 6);
else if (time.substr(0, 2) == "11") cout << "23" + time.substr(2, 6);
else cout << time.substr(0, 8);
}
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/vector_erase.cpp
================================================
#include
#include
using namespace std;
int main() {
int time, temp, n;
vector v;
cin >> time;
while (time--) {
cin >> temp;
v.push_back(temp);
}
int bla, begin, end;
cin >> bla >> begin >> end;
cout << end - begin + 1 << endl;
v.erase(v.begin() + begin - 1, v.begin() + end);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/cpp/introduction/vector_sort.cpp
================================================
#include
#include
#include
using namespace std;
int main() {
vector v;
int n, temp;
cin >> n;
while (n--) {
cin >> temp;
v.push_back(temp);
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;
}
================================================
FILE: competitive-programming/hacker-rank/data_structures/trees/in_order_traversal.py
================================================
def in_order(node):
if node.left:
in_order(node.left)
print node.data,
if node.right:
in_order(node.right)
================================================
FILE: competitive-programming/hacker-rank/data_structures/trees/post_order_traversal.py
================================================
def post_order(node):
if node.left:
post_order(node.left)
if node.right:
post_order(node.right)
print(node.data)
================================================
FILE: competitive-programming/hacker-rank/data_structures/trees/pre_order_traversal.py
================================================
def pre_order(node):
print(node.data)
if node.left:
pre_order(node.left)
if node.right:
pre_order(node.right)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/array_of_n_elements/array_of_n_elements.clj
================================================
;; https://www.hackerrank.com/challenges/fp-array-of-n-elements/problem
(defn array-of-n-elements
[n]
(range n))
(array-of-n-elements 1)
(array-of-n-elements 3)
(array-of-n-elements 5)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/array_of_n_elements/array_of_n_elements_without_range.clj
================================================
;; https://www.hackerrank.com/challenges/fp-array-of-n-elements/problem
(defn array-of-n-elements-without-range
[n]
(loop [n n list []]
(if (pos? n)
(recur (dec n) (conj list 0))
list)))
(array-of-n-elements-without-range 1)
(array-of-n-elements-without-range 3)
(array-of-n-elements-without-range 5)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/basics/hello_world.clj
================================================
;; Problem: https://www.hackerrank.com/challenges/fp-hello-world/problem?h_r=next-challenge&h_v=zen
(print "Hello World")
================================================
FILE: competitive-programming/hacker-rank/functional-programming/basics/hello_world_n_times.clj
================================================
;; https://www.hackerrank.com/challenges/fp-hello-world-n-times/problem
(defn greater-than-zero? [n] (> n 0))
(defn hello-word-n-times
[n]
(if (greater-than-zero? n)
(do (println "Hello World")
(hello-word-n-times (dec n)))))
(hello-word-n-times 4)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/basics/solve_me_first.clj
================================================
;; Problem: https://www.hackerrank.com/challenges/fp-solve-me-first/problem
(defn solve-me-first
[a b]
(+ a b))
(def a (read-line))
(def b (read-line))
(println (solve-me-first (Integer/parseInt a) (Integer/parseInt b)))
================================================
FILE: competitive-programming/hacker-rank/functional-programming/eval_ex/main.clj
================================================
;; https://www.hackerrank.com/challenges/eval-ex/problem
;; Approach:
;; Use map to transform the list of 10 elements from x to (/ (exp x n) (factorial n))
;; And reduce suming each element
;; For this approach, we can separate in 3 different functions
;; - exp: exponantial
;; - factorial
;; - expansion: function composed of exp and factorial passed to map
;; So we can test these 3 functions
(ns eval-ex
(:use [clojure.test]))
(defn exp
[x n]
(reduce * (repeat n x)))
(defn factorial
[n]
(reduce * (range 1 (inc n))))
(defn expansion
[x]
(fn [n]
(/ (exp x n) (factorial n))))
(defn series-expansion
[x]
(read-string
(format "%.4f"
(reduce + (map (expansion x) (range 10))))))
;; -----------------------------------------------------------
;; Tests
(deftest test-exp
(testing "Exponantial function"
(is (= 1 (exp 1 0)))
(is (= 1 (exp 1 1)))
(is (= 4 (exp 2 2)))))
(deftest test-factorial
(testing "Factorial function"
(is (= 1 (factorial 0)))
(is (= 1 (factorial 1)))
(is (= 120 (factorial 5)))))
(deftest test-expansion
(testing "Expansion function"
(is (= 1 ((expansion 10) 0)))
(is (= 10 ((expansion 10) 1)))
(is (= 50 ((expansion 10) 2)))))
(deftest test-series-expansion
(testing "Sample Input - Output"
(is (= 2423600.1887 (series-expansion 20.0000)))
(is (= 143.6895 (series-expansion 5.0000)))
(is (= 1.6487 (series-expansion 0.5000)))
(is (= 0.6065 (series-expansion -0.5000)))))
(run-tests)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/filter_array/filter_array.clj
================================================
;; https://www.hackerrank.com/challenges/fp-filter-array/problem
(defn filter-array
[n lst]
(filter #(> n %) lst))
(filter-array 25 [-41 46 -28 21 52 83 -29 84 27 40])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/filter_positions_in_a_list/filter_positions_in_a_list.clj
================================================
;; https://www.hackerrank.com/challenges/fp-filter-positions-in-a-list/problem
(defn filter-positions-in-a-list
[lst]
(take-nth 2 (rest lst)))
(filter-positions-in-a-list [])
(filter-positions-in-a-list [0 1 2])
(filter-positions-in-a-list [0 1 2 3 4 5 6 7 8 9])
(filter-positions-in-a-list [8 15 22 1 10 6 2 18 18 1])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/list_length/list_length.clj
================================================
;; https://www.hackerrank.com/challenges/fp-list-length/problem?h_r=next-challenge&h_v=zen
(defn list-length
[lst]
(loop [coll lst counter 0]
(if (empty? coll)
counter
(recur (rest coll) (inc counter)))))
(list-length [0 1 2 3 4 5 6 7 8 9])
(list-length [0 1 2 -1 4 -5 6 7 -8 9])
(list-length [])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/list_length/list_length_reduce.clj
================================================
;; https://www.hackerrank.com/challenges/fp-list-length/problem?h_r=next-challenge&h_v=zen
(defn list-length
[lst]
(reduce + (map (constantly 1) lst)))
(list-length [0 1 2 3 4 5 6 7 8 9])
(list-length [0 1 2 -1 4 -5 6 7 -8 9])
(list-length [])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/list_replication/list_replication.clj
================================================
;; Problem: https://www.hackerrank.com/challenges/fp-list-replication/problem
(defn list-replication
[n list]
(sort
(flatten
(repeat n list))))
(list-replication 3 [1 2 3])
(list-replication 2 [4 5])
(list-replication 1 [10 100])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list.clj
================================================
;; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem
;; last function: returns the last element of a collection
;; count function: returns the length of a collection
;; take function: returns the first N taken elements of a collection
;; not-empty function: returns true if the collection is not empty. Otherwise, false
(def example-list [19 22 3 28 26 17 18 4 28 0])
(defn reverse-a-list
[list]
(loop [original-list list reversed-list []]
(if (not-empty original-list)
(recur (take (dec (count original-list)) original-list) (conj reversed-list (last original-list)))
reversed-list)))
(reverse-a-list example-list)
;; Implementing an anonymous function
(fn [lst]
(loop [original-list lst reversed-list []]
(if (not-empty original-list)
(recur (take (dec (count original-list)) original-list) (conj reversed-list (last original-list)))
reversed-list)))
================================================
FILE: competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list_into.clj
================================================
;; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem
;; basically, the into function is a reduce + conj
(def example-list [19 22 3 28 26 17 18 4 28 0])
(defn reverse-a-list
[lst]
(into '() lst))
(reverse-a-list example-list)
((fn [lst] (into '() lst)) example-list)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list_reduce.clj
================================================
;; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem
(def example-list [19 22 3 28 26 17 18 4 28 0])
(defn reverse-a-list
[lst]
(reduce conj '() lst))
(reverse-a-list example-list)
;; Implementing an anonymous function
((fn [lst] (reduce conj '() lst)) example-list)
================================================
FILE: competitive-programming/hacker-rank/functional-programming/sum_of_odd_elements/sum_of_odd_elements.clj
================================================
;; https://www.hackerrank.com/challenges/fp-sum-of-odd-elements/problem
(defn sum-of-odd-elements
[lst]
(reduce
+
(filter
(odd? n)
lst)))
(sum-of-odd-elements [3 2 4 6 5 7 8 0 1])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list.clj
================================================
;; https://www.hackerrank.com/challenges/fp-update-list/problem
(defn to-absolute
[n]
(if (neg? n)
(+ (* n -2) n)
n))
(defn add-element-from-list-to-list
[lst1 lst2]
(conj lst2 (to-absolute (first lst1))))
(defn update-list
[lst]
(loop [original-list lst absolute-list []]
(if (empty? original-list)
absolute-list
(recur
(rest original-list)
(add-element-from-list-to-list original-list absolute-list)))))
(update-list [])
(update-list [1 2 3 4 5])
(update-list [-1 -2 -3 -4 -5])
(update-list [1 -2 3 -4 5])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list_anonymous.clj
================================================
;; https://www.hackerrank.com/challenges/fp-update-list/problem
(fn
[lst]
(loop [original-list lst absolute-list []]
(if (empty? original-list)
absolute-list
(recur
(rest original-list)
(conj
absolute-list
(if (< (first original-list) 0)
(+ (* (first original-list) -2) (first original-list))
(first original-list)))))))
================================================
FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list_map.clj
================================================
;; https://www.hackerrank.com/challenges/fp-update-list/problem
(defn to-absolute
[n]
(if (neg? n)
(+ (* n -2) n)
n))
(defn update-list-map
[lst]
(map to-absolute lst))
(update-list-map [])
(update-list-map [1 2 3 4 5])
(update-list-map [-1 -2 -3 -4 -5])
(update-list-map [1 -2 3 -4 5])
================================================
FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list_map_anonymous.clj
================================================
;; https://www.hackerrank.com/challenges/fp-update-list/problem
(fn
[lst]
(map
(fn
[n]
(if (neg? n)
(+ (* n -2) n)
n))
lst))
================================================
FILE: competitive-programming/hacker-rank/python/basic_data_types/finding_the_percentage.py
================================================
# https://www.hackerrank.com/challenges/finding-the-percentage/problem
if __name__ == '__main__':
n = int(raw_input())
student_marks = {}
for _ in range(n):
line = raw_input().split()
name, scores = line[0], line[1:]
scores = map(float, scores)
student_marks[name] = scores
print('%.2f' %(sum(student_marks[raw_input()]) / 3))
================================================
FILE: competitive-programming/hacker-rank/python/basic_data_types/lists.py
================================================
if __name__ == '__main__':
N = int(raw_input())
l = []
for i in range(N):
u_input = raw_input().split(' ')
if u_input[0] == 'insert':
l.insert(int(u_input[1]), int(u_input[2]))
elif u_input[0] == 'remove':
l.remove(int(u_input[1]))
elif u_input[0] == 'append':
l.append(int(u_input[1]))
elif u_input[0] == 'sort':
l.sort()
elif u_input[0] == 'pop':
l.pop()
elif u_input[0] == 'reverse':
l.reverse()
else:
print(l)
================================================
FILE: competitive-programming/hacker-rank/python/basic_data_types/nested_list.py
================================================
# https://www.hackerrank.com/challenges/nested-list/problem
marksheet = [[raw_input(), float(raw_input())] for _ in range(int(raw_input()))]
second_lowest = sorted(list(set([score for name, score in marksheet])))[1]
names = sorted([name for name, score in marksheet if score == second_lowest])
for name in names:
print name
================================================
FILE: competitive-programming/hacker-rank/python/basic_data_types/runner_up_score.py
================================================
# [1,6,3,6,5,4]
# [1,-1]
# [6, 1]
# [6, 3]
# [6, 3]
# [6, 5]
# [6, 5]
if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
maximum = -999999999999999999999
runner_up = -999999999999999999999
for el in arr:
if el > maximum:
runner_up = maximum
maximum = el
elif el < maximum and el > runner_up:
runner_up = el
print(runner_up)
================================================
FILE: competitive-programming/hacker-rank/python/basic_data_types/tuple.py
================================================
# https://www.hackerrank.com/challenges/python-tuples/problem
if __name__ == '__main__':
n = int(raw_input())
integer_list = map(int, raw_input().split())
print(hash(tuple(integer_list)))
================================================
FILE: competitive-programming/hacker-rank/python/introduction/arithmetic_operators.py
================================================
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
print(a + b)
print(a - b)
print(a * b)
================================================
FILE: competitive-programming/hacker-rank/python/introduction/division.py
================================================
from __future__ import division
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
print(a // b)
print(a / b)
================================================
FILE: competitive-programming/hacker-rank/python/introduction/if_else.py
================================================
if __name__ == '__main__':
n = int(raw_input())
if n % 2 != 0:
print("Weird")
else:
if n >= 2 and n <= 5:
print("Not Weird")
elif n >= 6 and n <= 20:
print("Weird")
elif n > 20:
print("Not Weird")
================================================
FILE: competitive-programming/hacker-rank/python/sets/intro_to_sets.py
================================================
# https://www.hackerrank.com/challenges/py-introduction-to-sets/problem
def average(array):
return sum(list(set(array))) / float(len(set(array)))
================================================
FILE: competitive-programming/hacker-rank/python/strings/find_a_string.py
================================================
# https://www.hackerrank.com/challenges/find-a-string/problem
# ABCDCDC
# CDC
# 2
# ABCDCDCD
# CD
# 3
# ABCDCDC
# AD
# 0
def count_substring(string, sub_string):
counter = 0
for index in range(0, len(string) - len(sub_string) + 1):
if sub_string == string[index:index + len(sub_string)]:
counter += 1
return counter
print(count_substring('ABCDCDC', 'CDC'))
print(count_substring('ABCDCDCD', 'CD'))
print(count_substring('ABCDCDC', 'AD'))
================================================
FILE: competitive-programming/hacker-rank/python/strings/mutate_string.py
================================================
# https://www.hackerrank.com/challenges/python-mutations/problem
# abracadabra
# 5 k
# abrackdabra
def mutate_string(string, position, character):
mutated_string = ''
for i in range(len(string)):
if i == position:
mutated_string += character
else:
mutated_string += string[i]
return mutated_string
print(mutate_string('abracadabra', 5, 'k'))
================================================
FILE: competitive-programming/hacker-rank/python/strings/split_and_join.py
================================================
# https://www.hackerrank.com/challenges/python-string-split-and-join/problem
# this is a string => this-is-a-string
# 123 456 789 => 123-456-789
# ... ... ... => ...-...-...
def split_and_join(line):
new_line = ''
for c in line:
if c == ' ':
new_line += '-'
else:
new_line += c
return new_line
print(split_and_join('this is a string'))
print(split_and_join('123 456 789'))
print(split_and_join('... ... ...'))
print(split_and_join('... ... ... '))
================================================
FILE: competitive-programming/hacker-rank/python/strings/string_validators.py
================================================
# https://www.hackerrank.com/challenges/string-validators/problem
if __name__ == '__main__':
s = raw_input()
print(any(c.isalnum() for c in s))
print(any(c.isalpha() for c in s))
print(any(c.isdigit() for c in s))
print(any(c.islower() for c in s))
print(any(c.isupper() for c in s))
================================================
FILE: competitive-programming/hacker-rank/python/strings/swap_case.py
================================================
# https://www.hackerrank.com/challenges/swap-case/problem
# A - Z (65 - 90)
# a - z (97 - 122)
def swap_case(s):
difference = 32
swapped_s = ''
for i in s:
if ord(i) < 65 or (ord(i) > 90 and ord(i) < 97) or ord(i) > 122:
swapped_s += i
elif ord(i) <= 90:
swapped_s += chr(ord(i) + difference)
else:
swapped_s += chr(ord(i) - difference)
return swapped_s
print(swap_case('Www.HackerRank.com'))
print(swap_case('Pythonist 2'))
print(swap_case('HackerRank.com presents "Pythonist 2".'))
================================================
FILE: competitive-programming/hacker-rank/python/strings/text_wrap.py
================================================
# https://www.hackerrank.com/challenges/text-wrap/problem
import textwrap
def wrap(string, max_width):
wrapped_text = ''
for i in range(1, len(string) + 1):
if i % max_width == 0:
wrapped_text += string[i-1]
print(wrapped_text)
wrapped_text = ''
else:
wrapped_text += string[i-1]
return wrapped_text
print(wrap('ABCDEFGHIJKLIMNOQRSTUVWXYZ', 4))
================================================
FILE: competitive-programming/hacker-rank/python/strings/whats_your_name.py
================================================
# https://www.hackerrank.com/challenges/whats-your-name/problem
# Guido
# Rossum
# Hello Guido Rossum! You just delved into python.
def print_full_name(a, b):
print "Hello %s %s! You just delved into python." %(a, b)
print_full_name('Guido', 'Rossum')
================================================
FILE: competitive-programming/interfatecs/1_2016/a.cpp
================================================
#include
#include
#include
using namespace std;
int main() {
int marq, n, e;
string s;
while (cin >> marq) {
cin >> n;
cin.ignore();
getline(cin, s);
string st = s + s;
cin >> e;
e = e % n;
while(st.size() < marq) {
st += s;
}
if (marq > n) cout << st.substr(e, n) << endl;
else cout << st.substr(e, marq) << endl;
}
return 0;
}
================================================
FILE: competitive-programming/interfatecs/1_2016/b.cpp
================================================
#include
#include
#include
using namespace std;
int main() {
int n;
while (cin >> n && n != -1) {
cout << 31 % n << endl;
}
return 0;
}
================================================
FILE: competitive-programming/interfatecs/1_2016/g.cpp
================================================
#include
#include
#include
#include
#include
using namespace std;
int main() {
int n;
double bang;
cin >> n;
while (n--) {
vector v;
for (int i = 0; i < 12; i++) {
cin >> bang;
v.push_back(bang);
}
sort(v.begin(), v.end());
float total = 0;
for (int i = 3; i < 12; i++) {
total += v[i];
}
float media = total / 9;
if (media * 0.2 < 1.75) {
cout << "REPROVADO" << endl;
} else {
double coisa = ((5.75 - (media * 0.2)) / 0.8) * 2;
printf("%.1f\n", coisa);
}
}
return 0;
}
================================================
FILE: competitive-programming/interfatecs/1_2016/i.cpp
================================================
#include
#include
using namespace std;
int main() {
double br, ext, h, gastobr, gastoext, cam;
cin >> br >> ext >> h >> gastobr >> gastoext >> cam;
double bang = (br * h * (1 - gastobr / 100) * 1.01);
bang += (br * h * (1 - gastobr / 100) * 1.01 * 1.01 * 1.01);
bang += (br * h * (1 - gastobr / 100)* 1.01 * 1.01);
double bang2 = 0;
bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01);
bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01* 1.01);
bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01* 1.01* 1.01);
printf("%.2fBR %.2fES\n", (bang), bang2);
return 0;
}
================================================
FILE: competitive-programming/interfatecs/1_2018/a.cpp
================================================
// A
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include