From d01d71da430fe0ea88522712448a402167dd7985 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Thu, 28 Oct 2021 00:28:19 +0530 Subject: [PATCH 1/8] Move files to src and modify test --- {Arrays => src/Arrays}/2d-array-ds.js | 0 {Arrays => src/Arrays}/apple-and-orange.js | 0 {Arrays => src/Arrays}/array-manipulation.js | 0 {Arrays => src/Arrays}/birthday-cake-candles.js | 0 {Arrays => src/Arrays}/breaking-best-and-worst-records.js | 0 {Arrays => src/Arrays}/compare-the-triplets.js | 0 {Arrays => src/Arrays}/diagonal-difference.js | 0 {Arrays => src/Arrays}/jumping-on-the-clouds.js | 0 {Arrays => src/Arrays}/left-rotation.js | 0 {Arrays => src/Arrays}/minimum-swaps-2.js | 0 {Arrays => src/Arrays}/newyear-chaos.js | 0 {Arrays => src/Arrays}/sock-merchant.js | 0 {Data Structures => src/Data Structures}/cycle-detection.js | 0 .../Data Structures}/reverse-doubly-linked-list.js | 0 .../Dictionaries and Hashmaps}/count-triplet.js | 0 .../Dictionaries and Hashmaps}/custom-hashmap.js | 0 .../Dictionaries and Hashmaps}/frequency-queries.js | 0 .../Dictionaries and Hashmaps}/game-of-thrones.js | 0 .../Dictionaries and Hashmaps}/ransom-note.js | 0 .../Dictionaries and Hashmaps}/sherlock-and-anagrams.js | 0 .../Dictionaries and Hashmaps}/two-strings.js | 0 {Numbers => src/Numbers}/grading.js | 0 {Numbers => src/Numbers}/kangaroo.js | 0 {Numbers => src/Numbers}/plus-minus.js | 0 {Numbers => src/Numbers}/staircase.js | 0 {Sorting => src/Sorting}/bubble-sort.js | 0 {Sorting => src/Sorting}/mark-and-toys.js | 0 {Sorting => src/Sorting}/mini-max-sum.js | 0 {Strings => src/Strings}/alternating-characters.js | 0 {Strings => src/Strings}/counting-valleys.js | 0 {Strings => src/Strings}/hackerrank-in-string.js | 0 {Strings => src/Strings}/making-anagrams.js | 0 {Strings => src/Strings}/repeated-string.js | 0 {Strings => src/Strings}/sherlock-and-the-valid-string.js | 0 {Strings => src/Strings}/strong-password.js | 0 {Strings => src/Strings}/time-conversion.js | 0 test/Arrays/birthday-cake-candles.test.js | 2 +- test/Arrays/left-rotation.test.js | 2 +- test/Data Structures/cycle-detection.test.js | 2 +- test/Data Structures/reverse-doubly-linked-list.test.js | 2 +- test/Numbers/plus-minus.test.js | 2 +- test/Strings/hackerrank-in-string.test.js | 2 +- test/Strings/repeated-string.test.js | 2 +- test/Strings/strong-password.test.js | 2 +- test/Strings/time-conversion.test.js | 2 +- 45 files changed, 9 insertions(+), 9 deletions(-) rename {Arrays => src/Arrays}/2d-array-ds.js (100%) rename {Arrays => src/Arrays}/apple-and-orange.js (100%) rename {Arrays => src/Arrays}/array-manipulation.js (100%) rename {Arrays => src/Arrays}/birthday-cake-candles.js (100%) rename {Arrays => src/Arrays}/breaking-best-and-worst-records.js (100%) rename {Arrays => src/Arrays}/compare-the-triplets.js (100%) rename {Arrays => src/Arrays}/diagonal-difference.js (100%) rename {Arrays => src/Arrays}/jumping-on-the-clouds.js (100%) rename {Arrays => src/Arrays}/left-rotation.js (100%) rename {Arrays => src/Arrays}/minimum-swaps-2.js (100%) rename {Arrays => src/Arrays}/newyear-chaos.js (100%) rename {Arrays => src/Arrays}/sock-merchant.js (100%) rename {Data Structures => src/Data Structures}/cycle-detection.js (100%) rename {Data Structures => src/Data Structures}/reverse-doubly-linked-list.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/count-triplet.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/custom-hashmap.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/frequency-queries.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/game-of-thrones.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/ransom-note.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/sherlock-and-anagrams.js (100%) rename {Dictionaries and Hashmaps => src/Dictionaries and Hashmaps}/two-strings.js (100%) rename {Numbers => src/Numbers}/grading.js (100%) rename {Numbers => src/Numbers}/kangaroo.js (100%) rename {Numbers => src/Numbers}/plus-minus.js (100%) rename {Numbers => src/Numbers}/staircase.js (100%) rename {Sorting => src/Sorting}/bubble-sort.js (100%) rename {Sorting => src/Sorting}/mark-and-toys.js (100%) rename {Sorting => src/Sorting}/mini-max-sum.js (100%) rename {Strings => src/Strings}/alternating-characters.js (100%) rename {Strings => src/Strings}/counting-valleys.js (100%) rename {Strings => src/Strings}/hackerrank-in-string.js (100%) rename {Strings => src/Strings}/making-anagrams.js (100%) rename {Strings => src/Strings}/repeated-string.js (100%) rename {Strings => src/Strings}/sherlock-and-the-valid-string.js (100%) rename {Strings => src/Strings}/strong-password.js (100%) rename {Strings => src/Strings}/time-conversion.js (100%) diff --git a/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js similarity index 100% rename from Arrays/2d-array-ds.js rename to src/Arrays/2d-array-ds.js diff --git a/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js similarity index 100% rename from Arrays/apple-and-orange.js rename to src/Arrays/apple-and-orange.js diff --git a/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js similarity index 100% rename from Arrays/array-manipulation.js rename to src/Arrays/array-manipulation.js diff --git a/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js similarity index 100% rename from Arrays/birthday-cake-candles.js rename to src/Arrays/birthday-cake-candles.js diff --git a/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js similarity index 100% rename from Arrays/breaking-best-and-worst-records.js rename to src/Arrays/breaking-best-and-worst-records.js diff --git a/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js similarity index 100% rename from Arrays/compare-the-triplets.js rename to src/Arrays/compare-the-triplets.js diff --git a/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js similarity index 100% rename from Arrays/diagonal-difference.js rename to src/Arrays/diagonal-difference.js diff --git a/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js similarity index 100% rename from Arrays/jumping-on-the-clouds.js rename to src/Arrays/jumping-on-the-clouds.js diff --git a/Arrays/left-rotation.js b/src/Arrays/left-rotation.js similarity index 100% rename from Arrays/left-rotation.js rename to src/Arrays/left-rotation.js diff --git a/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js similarity index 100% rename from Arrays/minimum-swaps-2.js rename to src/Arrays/minimum-swaps-2.js diff --git a/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js similarity index 100% rename from Arrays/newyear-chaos.js rename to src/Arrays/newyear-chaos.js diff --git a/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js similarity index 100% rename from Arrays/sock-merchant.js rename to src/Arrays/sock-merchant.js diff --git a/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js similarity index 100% rename from Data Structures/cycle-detection.js rename to src/Data Structures/cycle-detection.js diff --git a/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js similarity index 100% rename from Data Structures/reverse-doubly-linked-list.js rename to src/Data Structures/reverse-doubly-linked-list.js diff --git a/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js similarity index 100% rename from Dictionaries and Hashmaps/count-triplet.js rename to src/Dictionaries and Hashmaps/count-triplet.js diff --git a/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js similarity index 100% rename from Dictionaries and Hashmaps/custom-hashmap.js rename to src/Dictionaries and Hashmaps/custom-hashmap.js diff --git a/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js similarity index 100% rename from Dictionaries and Hashmaps/frequency-queries.js rename to src/Dictionaries and Hashmaps/frequency-queries.js diff --git a/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js similarity index 100% rename from Dictionaries and Hashmaps/game-of-thrones.js rename to src/Dictionaries and Hashmaps/game-of-thrones.js diff --git a/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js similarity index 100% rename from Dictionaries and Hashmaps/ransom-note.js rename to src/Dictionaries and Hashmaps/ransom-note.js diff --git a/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js similarity index 100% rename from Dictionaries and Hashmaps/sherlock-and-anagrams.js rename to src/Dictionaries and Hashmaps/sherlock-and-anagrams.js diff --git a/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js similarity index 100% rename from Dictionaries and Hashmaps/two-strings.js rename to src/Dictionaries and Hashmaps/two-strings.js diff --git a/Numbers/grading.js b/src/Numbers/grading.js similarity index 100% rename from Numbers/grading.js rename to src/Numbers/grading.js diff --git a/Numbers/kangaroo.js b/src/Numbers/kangaroo.js similarity index 100% rename from Numbers/kangaroo.js rename to src/Numbers/kangaroo.js diff --git a/Numbers/plus-minus.js b/src/Numbers/plus-minus.js similarity index 100% rename from Numbers/plus-minus.js rename to src/Numbers/plus-minus.js diff --git a/Numbers/staircase.js b/src/Numbers/staircase.js similarity index 100% rename from Numbers/staircase.js rename to src/Numbers/staircase.js diff --git a/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js similarity index 100% rename from Sorting/bubble-sort.js rename to src/Sorting/bubble-sort.js diff --git a/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js similarity index 100% rename from Sorting/mark-and-toys.js rename to src/Sorting/mark-and-toys.js diff --git a/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js similarity index 100% rename from Sorting/mini-max-sum.js rename to src/Sorting/mini-max-sum.js diff --git a/Strings/alternating-characters.js b/src/Strings/alternating-characters.js similarity index 100% rename from Strings/alternating-characters.js rename to src/Strings/alternating-characters.js diff --git a/Strings/counting-valleys.js b/src/Strings/counting-valleys.js similarity index 100% rename from Strings/counting-valleys.js rename to src/Strings/counting-valleys.js diff --git a/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js similarity index 100% rename from Strings/hackerrank-in-string.js rename to src/Strings/hackerrank-in-string.js diff --git a/Strings/making-anagrams.js b/src/Strings/making-anagrams.js similarity index 100% rename from Strings/making-anagrams.js rename to src/Strings/making-anagrams.js diff --git a/Strings/repeated-string.js b/src/Strings/repeated-string.js similarity index 100% rename from Strings/repeated-string.js rename to src/Strings/repeated-string.js diff --git a/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js similarity index 100% rename from Strings/sherlock-and-the-valid-string.js rename to src/Strings/sherlock-and-the-valid-string.js diff --git a/Strings/strong-password.js b/src/Strings/strong-password.js similarity index 100% rename from Strings/strong-password.js rename to src/Strings/strong-password.js diff --git a/Strings/time-conversion.js b/src/Strings/time-conversion.js similarity index 100% rename from Strings/time-conversion.js rename to src/Strings/time-conversion.js diff --git a/test/Arrays/birthday-cake-candles.test.js b/test/Arrays/birthday-cake-candles.test.js index ba2fb31..5d43aba 100644 --- a/test/Arrays/birthday-cake-candles.test.js +++ b/test/Arrays/birthday-cake-candles.test.js @@ -1,4 +1,4 @@ -const birthdayCakeCandles = require("../../Arrays/birthday-cake-candles"); +const birthdayCakeCandles = require("../../src/Arrays/birthday-cake-candles"); const { describe, it } = require("mocha"); const { expect } = require("chai"); diff --git a/test/Arrays/left-rotation.test.js b/test/Arrays/left-rotation.test.js index f1dd855..2a4e66a 100644 --- a/test/Arrays/left-rotation.test.js +++ b/test/Arrays/left-rotation.test.js @@ -1,4 +1,4 @@ -const leftRotation = require('../../Arrays/left-rotation') +const leftRotation = require('../../src/Arrays/left-rotation') const { describe, it } = require('mocha') const { expect } = require('chai') diff --git a/test/Data Structures/cycle-detection.test.js b/test/Data Structures/cycle-detection.test.js index a465729..32fdcb7 100644 --- a/test/Data Structures/cycle-detection.test.js +++ b/test/Data Structures/cycle-detection.test.js @@ -1,4 +1,4 @@ -const { hasCycle, Node } = require('../../Data Structures/cycle-detection'); +const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); const { describe, it } = require('mocha'); const { expect } = require('chai'); diff --git a/test/Data Structures/reverse-doubly-linked-list.test.js b/test/Data Structures/reverse-doubly-linked-list.test.js index f23567b..4acc443 100644 --- a/test/Data Structures/reverse-doubly-linked-list.test.js +++ b/test/Data Structures/reverse-doubly-linked-list.test.js @@ -1,4 +1,4 @@ -const { reverse, DoublyLinkedListNode, DoublyLinkedList } = require('../../Data Structures/reverse-doubly-linked-list'); +const { reverse, DoublyLinkedListNode, DoublyLinkedList } = require('../../src/Data Structures/reverse-doubly-linked-list'); const { describe, it } = require('mocha') const { expect } = require('chai') diff --git a/test/Numbers/plus-minus.test.js b/test/Numbers/plus-minus.test.js index aa7ab29..7fa3ced 100644 --- a/test/Numbers/plus-minus.test.js +++ b/test/Numbers/plus-minus.test.js @@ -1,4 +1,4 @@ -const plusMinus = require('../../Numbers/plus-minus') +const plusMinus = require('../../src/Numbers/plus-minus') const { describe, it } = require('mocha') const { expect } = require('chai') diff --git a/test/Strings/hackerrank-in-string.test.js b/test/Strings/hackerrank-in-string.test.js index 647c9a7..349627c 100644 --- a/test/Strings/hackerrank-in-string.test.js +++ b/test/Strings/hackerrank-in-string.test.js @@ -1,4 +1,4 @@ -const hackerrankInString = require("../../Strings/hackerrank-in-string"); +const hackerrankInString = require("../../src/Strings/hackerrank-in-string"); const { describe, it } = require("mocha"); const { expect } = require("chai"); diff --git a/test/Strings/repeated-string.test.js b/test/Strings/repeated-string.test.js index a797079..7003391 100644 --- a/test/Strings/repeated-string.test.js +++ b/test/Strings/repeated-string.test.js @@ -1,4 +1,4 @@ -const repeatedString = require("../../Strings/repeated-string"); +const repeatedString = require("../../src/Strings/repeated-string"); const { describe, it } = require("mocha"); const { expect } = require("chai"); diff --git a/test/Strings/strong-password.test.js b/test/Strings/strong-password.test.js index 2f44ed7..f9fec61 100644 --- a/test/Strings/strong-password.test.js +++ b/test/Strings/strong-password.test.js @@ -1,4 +1,4 @@ -const passwordStrengthMinimumNumber = require("../../Strings/strong-password"); +const passwordStrengthMinimumNumber = require("../../src/Strings/strong-password"); const { describe, it } = require("mocha"); const { expect } = require("chai"); diff --git a/test/Strings/time-conversion.test.js b/test/Strings/time-conversion.test.js index c89a1d1..16ba822 100644 --- a/test/Strings/time-conversion.test.js +++ b/test/Strings/time-conversion.test.js @@ -1,4 +1,4 @@ -const timeConversion = require("../../Strings/time-conversion"); +const timeConversion = require("../../src/Strings/time-conversion"); const { describe, it } = require("mocha"); const { expect } = require("chai"); From 16b1b2e457577e9119fc457f71a6e08f1d96e716 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Thu, 28 Oct 2021 00:42:35 +0530 Subject: [PATCH 2/8] Fix eslint and add eslint to travis --- .editorconfig | 4 +- .eslintrc.json | 55 +++++++------ .travis.yml | 4 +- package.json | 12 ++- src/Arrays/2d-array-ds.js | 28 ++++--- src/Arrays/apple-and-orange.js | 28 +++---- src/Arrays/array-manipulation.js | 18 ++-- src/Arrays/birthday-cake-candles.js | 24 +++--- src/Arrays/breaking-best-and-worst-records.js | 62 +++++++------- src/Arrays/compare-the-triplets.js | 20 ++--- src/Arrays/diagonal-difference.js | 25 +++--- src/Arrays/jumping-on-the-clouds.js | 31 ++++--- src/Arrays/left-rotation.js | 17 ++-- src/Arrays/minimum-swaps-2.js | 35 ++++---- src/Arrays/newyear-chaos.js | 36 ++++---- src/Arrays/sock-merchant.js | 36 ++++---- src/Data Structures/cycle-detection.js | 41 +++++----- .../reverse-doubly-linked-list.js | 82 +++++++++---------- .../count-triplet.js | 37 ++++----- .../custom-hashmap.js | 40 ++++----- .../frequency-queries.js | 58 ++++++------- .../game-of-thrones.js | 16 ++-- src/Dictionaries and Hashmaps/ransom-note.js | 71 ++++++++-------- .../sherlock-and-anagrams.js | 32 ++++---- src/Dictionaries and Hashmaps/two-strings.js | 25 +++--- src/Numbers/grading.js | 27 +++--- src/Numbers/kangaroo.js | 45 +++++----- src/Numbers/plus-minus.js | 34 ++++---- src/Numbers/staircase.js | 8 +- src/Sorting/bubble-sort.js | 30 +++---- src/Sorting/mark-and-toys.js | 31 +++---- src/Sorting/mini-max-sum.js | 14 ++-- src/Strings/alternating-characters.js | 26 +++--- src/Strings/counting-valleys.js | 34 ++++---- src/Strings/hackerrank-in-string.js | 16 ++-- src/Strings/making-anagrams.js | 73 ++++++++--------- src/Strings/repeated-string.js | 16 ++-- src/Strings/sherlock-and-the-valid-string.js | 61 +++++++------- src/Strings/strong-password.js | 32 +++----- src/Strings/time-conversion.js | 31 ++++--- 40 files changed, 652 insertions(+), 663 deletions(-) diff --git a/.editorconfig b/.editorconfig index 1a6d62e..3281cce 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,9 +6,9 @@ end_of_line = lf indent_size = 2 indent_style = tab insert_final_newline = true -max_line_length = 130 +max_line_length = 155 trim_trailing_whitespace = true [*.md] -max_line_length = 130 +max_line_length = 155 trim_trailing_whitespace = true diff --git a/.eslintrc.json b/.eslintrc.json index fd4d4cf..a9d94b6 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,27 +1,30 @@ { - "env": { - "browser": true, - "commonjs": true, - "es2021": true - }, - "extends": [ - "eslint:recommended", - "airbnb-base" - ], - "parserOptions": { - "ecmaVersion": 12 - }, - "rules": { - "indent": ["error", "tab"], - "no-tabs": ["error", { "allowIndentationTabs": true }], - "max-len": ["error", { "code": 130 }], - "no-var": "error", - "semi": "error", - "no-multi-spaces": "error", - "space-in-parens": "error", - "no-multiple-empty-lines": "error", - "prefer-const": "error", - "no-use-before-define": "error" - } - } - + "env": { + "browser": true, + "commonjs": true, + "es2021": true + }, + "extends": ["eslint:recommended", "airbnb-base"], + "parserOptions": { + "ecmaVersion": 12 + }, + "rules": { + "indent": ["error", "tab"], + "no-tabs": ["warn", { "allowIndentationTabs": true }], + "max-len": ["error", { "code": 155 }], + "no-var": "error", + "semi": "error", + "no-multi-spaces": "error", + "space-in-parens": "error", + "no-multiple-empty-lines": "error", + "prefer-const": "error", + "no-use-before-define": "error", + "max-classes-per-file": ["warn", 1], + "no-plusplus": "off", + "no-param-reassign": "warn", + "no-restricted-syntax": "warn", + "no-continue": "warn", + "no-bitwise": "off", + "guard-for-in": "warn" + } +} diff --git a/.travis.yml b/.travis.yml index 9ef231a..437f211 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,5 +5,5 @@ node_js: install: - npm install script: -- npm run test -- npm run lint + - npm run test + - eslint src test --ext .js diff --git a/package.json b/package.json index f9db512..c819338 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,15 @@ "version": "1.0.0", "description": "Solutions for HackerRank Problems in Javascript.", "main": "index.js", + "nyc": { + "all": true, + "include": [ + "src/**/*.js" + ] + }, "scripts": { - "test": "mocha --recursive", - "report": "nyc mocha --recursive", - "prepare": "husky install", - "lint": "prettier --write **/*.*js && eslint --fix " + "test": "nyc mocha --recursive", + "prepare": "husky install" }, "lint-staged": { "*.js": [ diff --git a/src/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js index 1e5a28e..398f4fd 100644 --- a/src/Arrays/2d-array-ds.js +++ b/src/Arrays/2d-array-ds.js @@ -4,14 +4,20 @@ Score: 15 Link: https://www.hackerrank.com/challenges/2d-array/ */ -function hourglassSum(arr) { - var sum = -1000 - let max = sum - for(let i = 0 ; i<4;i++){ - for(let j = 0 ; j<4; j++){ - sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] - if(sum>max) max = sum - } - } - console.log(max) -} +module.exports = function hourglassSum(arr) { + let sum = -1000; + let max = sum; + for (let i = 0; i < 4; i++) { + for (let j = 0; j < 4; j++) { + sum = arr[i][j] + + arr[i][j + 1] + + arr[i][j + 2] + + arr[i + 1][j + 1] + + arr[i + 2][j] + + arr[i + 2][j + 1] + + arr[i + 2][j + 2]; + if (sum > max) max = sum; + } + } + console.log(max); +}; diff --git a/src/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js index ffaf16a..3aea64e 100644 --- a/src/Arrays/apple-and-orange.js +++ b/src/Arrays/apple-and-orange.js @@ -4,23 +4,21 @@ Score: 10 Link: https://www.hackerrank.com/challenges/apple-and-orange */ - -function countApplesAndOranges(s, t, a, b, apples, oranges) { - countFruitsFallInsideHome(apples, s - a, t - a); - countFruitsFallInsideHome(oranges, s - b, t - b); -} - - function countFruitsFallInsideHome(fruits, startHome, EndHome) { - let counter = 0; - fruits.forEach(fruit => { - if (fruit >= startHome && fruit <= EndHome) { - return counter++; - } - }); + let counter = 0; + fruits.forEach((fruit) => { + if (fruit >= startHome && fruit <= EndHome) { + counter++; + } + return counter; + }); - return console.log(counter); + return console.log(counter); } -countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1] , [5 -6]); +function countApplesAndOranges(s, t, a, b, apples, oranges) { + countFruitsFallInsideHome(apples, s - a, t - a); + countFruitsFallInsideHome(oranges, s - b, t - b); +} +countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1], [5 - 6]); diff --git a/src/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js index 45eaf1d..a04ae2b 100644 --- a/src/Arrays/array-manipulation.js +++ b/src/Arrays/array-manipulation.js @@ -5,14 +5,14 @@ Link: https://www.hackerrank.com/challenges/crush/problem */ -function arrayManipulation(n, queries) { - let arr = Array(n).fill(0); +module.exports = function arrayManipulation(n, queries) { + const arr = Array(n).fill(0); - for (let a = 0; a < queries.length; a++) { - for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { - arr[index] += queries[a][2]; - } - } + for (let a = 0; a < queries.length; a++) { + for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { + arr[index] += queries[a][2]; + } + } - return Math.max(...arr); -} + return Math.max(...arr); +}; diff --git a/src/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js index 35ed0d7..674311e 100644 --- a/src/Arrays/birthday-cake-candles.js +++ b/src/Arrays/birthday-cake-candles.js @@ -6,16 +6,16 @@ */ module.exports = function birthdayCakeCandles(arr) { - let tallestCandle = 0; - let candlesCounter = 0; - for (let index = 0; index < arr.length; index++) { - if (arr[index] > tallestCandle) { - tallestCandle = arr[index]; - candlesCounter = 1; - } else if (arr[index] === tallestCandle) { - candlesCounter++; - } - } + let tallestCandle = 0; + let candlesCounter = 0; + for (let index = 0; index < arr.length; index++) { + if (arr[index] > tallestCandle) { + tallestCandle = arr[index]; + candlesCounter = 1; + } else if (arr[index] === tallestCandle) { + candlesCounter++; + } + } - return candlesCounter; -} + return candlesCounter; +}; diff --git a/src/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js index 1afad77..9df7f33 100644 --- a/src/Arrays/breaking-best-and-worst-records.js +++ b/src/Arrays/breaking-best-and-worst-records.js @@ -6,37 +6,35 @@ */ function breakingRecords(scores) { - - let counters = { - min: 0, - max: 0 - }; - - let values = { - min: 0, - max: 0 - } - let isDefaultSet = false; - - scores.forEach(score => { - if (!isDefaultSet) { - values.min = score; - values.max = score; - isDefaultSet = true; - return ; - } - - if (score > values.max) { - values.max = score; - counters.max++; - } else if (score < values.min) { - values.min = score; - counters.min++; - } - }) - - return [counters.max, counters.min]; - + const counters = { + min: 0, + max: 0, + }; + + const values = { + min: 0, + max: 0, + }; + let isDefaultSet = false; + + scores.forEach((score) => { + if (!isDefaultSet) { + values.min = score; + values.max = score; + isDefaultSet = true; + return; + } + + if (score > values.max) { + values.max = score; + counters.max++; + } else if (score < values.min) { + values.min = score; + counters.min++; + } + }); + + return [counters.max, counters.min]; } -breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]) +breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]); diff --git a/src/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js index 75d6007..b542423 100644 --- a/src/Arrays/compare-the-triplets.js +++ b/src/Arrays/compare-the-triplets.js @@ -6,16 +6,16 @@ Link: https://www.hackerrank.com/challenges/compare-the-triplets/problem */ function compareTriplets(a, b) { - let points = [0, 0]; - for (let index = 0; index < a.length; index++){ - if (a[index] > b[index]) { - points[0] += 1; - } else if (a[index] < b[index]) { - points[1] += 1; - } - } + const points = [0, 0]; + for (let index = 0; index < a.length; index++) { + if (a[index] > b[index]) { + points[0] += 1; + } else if (a[index] < b[index]) { + points[1] += 1; + } + } - return points; + return points; } -console.log(compareTriplets([5, 6, 7], [3, 6, 10])) +console.log(compareTriplets([5, 6, 7], [3, 6, 10])); diff --git a/src/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js index 336b05d..a8290c3 100644 --- a/src/Arrays/diagonal-difference.js +++ b/src/Arrays/diagonal-difference.js @@ -1,4 +1,3 @@ - /* Title:Diagonal Difference Difficulty: Easy @@ -7,16 +6,20 @@ */ function diagonalDifference(arr) { - let leftToRight = 0; - let rightToLeft = 0; - let tmpLength = arr.length; - for (let i = 0; i < arr.length; i++){ - leftToRight += arr[i][i]; - rightToLeft += arr[i][--tmpLength]; - } + let leftToRight = 0; + let rightToLeft = 0; + let tmpLength = arr.length; + for (let i = 0; i < arr.length; i++) { + leftToRight += arr[i][i]; + rightToLeft += arr[i][--tmpLength]; + } - return Math.abs(leftToRight - rightToLeft); + return Math.abs(leftToRight - rightToLeft); } -let input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] -console.log(diagonalDifference(input)) +const input = [ + [11, 2, 4], + [4, 5, 6], + [10, 8, -12], +]; +console.log(diagonalDifference(input)); diff --git a/src/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js index 9f5c7d1..0488a2f 100644 --- a/src/Arrays/jumping-on-the-clouds.js +++ b/src/Arrays/jumping-on-the-clouds.js @@ -5,20 +5,19 @@ Link: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ */ -function jumpingOnClouds(c) { +module.exports = function jumpingOnClouds(c) { + let jump = 0; + for (let i = 0; i < c.length;) { + if (c[i + 2] === 0) { + jump++; + i += 2; + } else if (c[i + 1] === 0) { + jump++; + i += 1; + } else { + i++; + } + } - let jump = 0; - for (let i = 0; i < c.length;){ - if (c[i + 2] == 0) { - jump++; - i += 2; - } else if (c[i + 1] == 0) { - jump++; - i += 1; - } else { - i++; - } - } - - return jump; -} + return jump; +}; diff --git a/src/Arrays/left-rotation.js b/src/Arrays/left-rotation.js index 17ed7de..7881ba7 100644 --- a/src/Arrays/left-rotation.js +++ b/src/Arrays/left-rotation.js @@ -6,14 +6,13 @@ */ module.exports = function rotLeft(a, d) { + if (!a.length) { + return []; + } - if(!a.length){ - return [] - } + for (let i = 0; i < d; i++) { + a.push(a.shift()); + } - for (let i = 0; i < d; i++) { - a.push(a.shift()); - } - - return a; -} + return a; +}; diff --git a/src/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js index c382556..95c93fc 100644 --- a/src/Arrays/minimum-swaps-2.js +++ b/src/Arrays/minimum-swaps-2.js @@ -5,22 +5,21 @@ Link: https://www.hackerrank.com/challenges/minimum-swaps-2 */ +module.exports = function minimumSwaps(arr) { + const origArray = arr.slice(0); + const sortedArray = arr.sort((a, b) => a - b); + let numberOfSwap = 0; + for (let i = 0; i < origArray.length; i++) { + if (origArray[i] !== sortedArray[i]) { + for (let j = i + 1; j < origArray.length; j++) { + if (origArray[j] === sortedArray[i]) { + [origArray[i], origArray[j]] = [origArray[j], origArray[i]]; + numberOfSwap++; + break; + } + } + } + } -function minimumSwaps(arr) { - var origArray = arr.slice(0); - var sortedArray = arr.sort((a,b) => a-b); - let numberOfSwap = 0; - for (var i = 0; i < origArray.length; i++) { - if (origArray[i] != sortedArray[i]) { - for (var j = i + 1; j < origArray.length; j++) { - if (origArray[j] === sortedArray[i]) { - [origArray[i], origArray[j]] = [origArray[j], origArray[i]] - numberOfSwap++ - break; - } - } - } - } - - return numberOfSwap; -} + return numberOfSwap; +}; diff --git a/src/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js index 0ae6270..e9a022f 100644 --- a/src/Arrays/newyear-chaos.js +++ b/src/Arrays/newyear-chaos.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/new-year-chaos/ */ -function minimumBribes(q) { - let swaps = 0; - let min = q.length; - for (var i = q.length -1 ; i >= 0; i--) { - if (q[i] - i > 3) { - return `Too chaotic`; - } - if (q[i] > i + 1) { - swaps += (q[i] - (i + 1)); - } else { - if (min > q[i]) { - min = q[i]; - } else if (q[i] != min) { - swaps++; - } - } - } +module.exports = function minimumBribes(q) { + let swaps = 0; + let min = q.length; + for (let i = q.length - 1; i >= 0; i--) { + if (q[i] - i > 3) { + return 'Too chaotic'; + } + if (q[i] > i + 1) { + swaps += q[i] - (i + 1); + } else if (min > q[i]) { + min = q[i]; + } else if (q[i] !== min) { + swaps++; + } + } - return swaps; -} + return swaps; +}; diff --git a/src/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js index e865834..c75cf50 100644 --- a/src/Arrays/sock-merchant.js +++ b/src/Arrays/sock-merchant.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/sock-merchant */ +module.exports = function sockMerchant(n, ar) { + const tmpArr = []; + let counter = 0; + ar.map((value) => { + if (tmpArr.includes(value)) { + const index = tmpArr.indexOf(value); + if (index > -1) { + tmpArr.splice(index, 1); + } + counter++; + } else { + tmpArr.push(value); + } + return value; + }); -function sockMerchant(n, ar) { - let tmpArr = []; - let counter = 0; - ar.map(value => { - if (tmpArr.includes(value)) { - var index = tmpArr.indexOf(value); - if (index > -1) { - tmpArr.splice(index, 1); - } - counter++; - } else { - tmpArr.push(value); - } - - }) - - return counter; - -} + return counter; +}; diff --git a/src/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js index 5bd280a..ed53bab 100644 --- a/src/Data Structures/cycle-detection.js +++ b/src/Data Structures/cycle-detection.js @@ -6,30 +6,33 @@ */ function hasCycle(head) { - if (head === null || head.next === null || head.next.next === null) return false; // edge cases - let hare = head; - let tortoise = head; - do { - hare = hare.next.next; // 'hare' moves twice per tick - tortoise = tortoise.next; // 'tortoise' moves once per tick - } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); - return hare === tortoise; + if (head === null || head.next === null || head.next.next === null) { + return false; + } // edge cases + let hare = head; + let tortoise = head; + do { + hare = hare.next.next; // 'hare' moves twice per tick + tortoise = tortoise.next; // 'tortoise' moves once per tick + } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); + return hare === tortoise; } // NODE CLASS class Node { - constructor (data) { - this.data = data; - this.next = null; - } - insert (data) { - this.next = new Node(data); - return this.next; // for chaining - } + constructor(data) { + this.data = data; + this.next = null; + } + + insert(data) { + this.next = new Node(data); + return this.next; // for chaining + } } module.exports = { - hasCycle, - Node, -}; \ No newline at end of file + hasCycle, + Node, +}; diff --git a/src/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js index 04dcde3..71a4f23 100644 --- a/src/Data Structures/reverse-doubly-linked-list.js +++ b/src/Data Structures/reverse-doubly-linked-list.js @@ -1,56 +1,52 @@ -'use strict'; /* Title: Reverse a doubly linked list Difficulty: Easy Score: 5 Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem */ - - -function reverse(head) { - while (head.next) { - head = head.next - } - - const newList = new DoublyLinkedList(); - - while (head) { - newList.insertNode(head.data); - head = head.prev - } - return newList.head -} - class DoublyLinkedListNode { - constructor(nodeData) { - this.data = nodeData; - this.next = null; - this.prev = null; - } -}; + constructor(nodeData) { + this.data = nodeData; + this.next = null; + this.prev = null; + } +} class DoublyLinkedList { - constructor() { - this.head = null; - this.tail = null; - } - - insertNode(nodeData) { - let node = new DoublyLinkedListNode(nodeData); + constructor() { + this.head = null; + this.tail = null; + } + + insertNode(nodeData) { + const node = new DoublyLinkedListNode(nodeData); + + if (this.head == null) { + this.head = node; + } else { + this.tail.next = node; + node.prev = this.tail; + } + + this.tail = node; + } +} - if (this.head == null) { - this.head = node; - } else { - this.tail.next = node; - node.prev = this.tail; - } +function reverse(head) { + while (head.next) { + head = head.next; + } - this.tail = node; - } -}; + const newList = new DoublyLinkedList(); -module.exports = { - reverse, - DoublyLinkedList, - DoublyLinkedListNode + while (head) { + newList.insertNode(head.data); + head = head.prev; + } + return newList.head; } +module.exports = { + reverse, + DoublyLinkedList, + DoublyLinkedListNode, +}; diff --git a/src/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js index ac8d48c..38656ad 100644 --- a/src/Dictionaries and Hashmaps/count-triplet.js +++ b/src/Dictionaries and Hashmaps/count-triplet.js @@ -6,30 +6,29 @@ */ function countTriplets(arr, r) { - let second = {} - let third = {} - let count = 0; - for (let index = 0; index < arr.length; index++) { + const second = {}; + const third = {}; + let count = 0; + for (let index = 0; index < arr.length; index++) { + const val = arr[index]; - const val = arr[index]; + // If value found on third then add it to count + if (third[val]) { + count += third[val]; + } - //If value found on third then add it to count - if(third[val]){ - count += third[val]; - } + // If value found on second , convey it to third - //If value found on second , convey it to third + if (second[val]) { + third[val * r] = third[val * r] + second[val] || second[val]; + } - if(second[val]){ - third[val*r] = third[val*r] + second[val] || second[val]; - } + // add current element into second value - //add current element into second value + second[val * r] = second[val * r] + 1 || 1; + } - second[val*r] = second[val*r]+1 || 1; - } - - return count; + return count; } -console.log(countTriplets([1,2 ,2,4], 2)); +console.log(countTriplets([1, 2, 2, 4], 2)); diff --git a/src/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js index c2431ec..f7a2fe6 100644 --- a/src/Dictionaries and Hashmaps/custom-hashmap.js +++ b/src/Dictionaries and Hashmaps/custom-hashmap.js @@ -5,31 +5,31 @@ Link: - */ class customHashMap { - constructor() { - this.list = []; - } + constructor() { + this.list = []; + } - get(x) { - return this.list[this.hashCode(x)]; - } + get(x) { + return this.list[this.hashCode(x)]; + } - set(x, y) { - this.list[this.hashCode(x)] = y; - } + set(x, y) { + this.list[this.hashCode(x)] = y; + } - hashCode(str) { - let hash = 0; - if (str.length == 0) return hash; - for (let i = 0; i < str.length; i++) { - let char = str.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash = hash & hash; // Convert to 32bit integer - } - return hash; - } + static hashCode(str) { + let hash = 0; + if (str.length === 0) return hash; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash &= hash; // Convert to 32bit integer + } + return hash; + } } -let m = new customHashMap(); +const m = customHashMap(); m.set('hello', 'world'); console.log(m.get('hello')); diff --git a/src/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js index c3f4d5a..40ccb6b 100644 --- a/src/Dictionaries and Hashmaps/frequency-queries.js +++ b/src/Dictionaries and Hashmaps/frequency-queries.js @@ -6,40 +6,40 @@ */ function freqQuery(arr) { - const result = []; - const hash = {}; - const freq = []; + const result = []; + const hash = {}; + const freq = []; - for (let i = 0; i < arr.length; i += 1) { - const [action, value] = arr[i]; - const initValue = hash[value] || 0; + for (let i = 0; i < arr.length; i += 1) { + const [action, value] = arr[i]; + const initValue = hash[value] || 0; - if (action === 1) { - hash[value] = initValue + 1; - freq[initValue] = (freq[initValue] || 0) - 1; - freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; - } + if (action === 1) { + hash[value] = initValue + 1; + freq[initValue] = (freq[initValue] || 0) - 1; + freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; + } - if (action === 2 && initValue > 0) { - hash[value] = initValue - 1; - freq[initValue - 1] += 1; - freq[initValue] -= 1; - } + if (action === 2 && initValue > 0) { + hash[value] = initValue - 1; + freq[initValue - 1] += 1; + freq[initValue] -= 1; + } - if (action === 3) result.push(freq[value] > 0 ? 1 : 0); - } + if (action === 3) result.push(freq[value] > 0 ? 1 : 0); + } - return result; + return result; } -let input = [ - [1, 5], - [1, 6], - [3, 2], - [1, 10], - [1, 10], - [1, 6], - [2, 5], - [3, 2] - ]; +const input = [ + [1, 5], + [1, 6], + [3, 2], + [1, 10], + [1, 10], + [1, 6], + [2, 5], + [3, 2], +]; console.log(freqQuery(input)); diff --git a/src/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js index 0d50f1e..d516d12 100644 --- a/src/Dictionaries and Hashmaps/game-of-thrones.js +++ b/src/Dictionaries and Hashmaps/game-of-thrones.js @@ -6,12 +6,14 @@ */ function gameOfThrones(s) { - const frequencies = {}; - for (let char of s) frequencies[char] = frequencies[char] + 1 || 1; - let oddFrequencies = Object.values(frequencies).filter(frequency => frequency % 2); - return oddFrequencies.length <= 1 ? 'YES' : 'NO'; + const frequencies = {}; + for (const char of s) frequencies[char] = frequencies[char] + 1 || 1; + const oddFrequencies = Object.values(frequencies).filter( + (frequency) => frequency % 2, + ); + return oddFrequencies.length <= 1 ? 'YES' : 'NO'; } -console.log(gameOfThrones('aaabbbb')); // YES -console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO -console.log(gameOfThrones('cdcdcdcdeeeef')); // YES \ No newline at end of file +console.log(gameOfThrones('aaabbbb')); // YES +console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO +console.log(gameOfThrones('cdcdcdcdeeeef')); // YES diff --git a/src/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js index bf7003a..2268c69 100644 --- a/src/Dictionaries and Hashmaps/ransom-note.js +++ b/src/Dictionaries and Hashmaps/ransom-note.js @@ -6,51 +6,48 @@ */ class ExtendedMap { - - constructor(){ - this.map = new Map(); - } - - get(x) { - let value = this.map.get(x); - if (value === 1) { - this.map.delete(x); - return true; - } - - return this.map.set(x, --value); - } - - set(x, y) { - if (this.map.get(x)) { - return this.map.set(x, this.map.get(x) + 1); - } - - return this.map.set(x, y); - } + constructor() { + this.map = new Map(); + } + + get(x) { + let value = this.map.get(x); + if (value === 1) { + this.map.delete(x); + return true; + } + + return this.map.set(x, --value); + } + + set(x, y) { + if (this.map.get(x)) { + return this.map.set(x, this.map.get(x) + 1); + } + + return this.map.set(x, y); + } } - function checkMagazine(magazine, note) { + const m = new ExtendedMap(); - let m = new ExtendedMap() - - for (let i = 0; i < magazine.length; i++) { - m.set(magazine[i], 1) - } + for (let i = 0; i < magazine.length; i++) { + m.set(magazine[i], 1); + } - for (let i = 0; i < note.length; i++) { - if (!m.get(note[i])) { - console.log('No'); - return; - }; - } + for (let i = 0; i < note.length; i++) { + if (!m.get(note[i])) { + console.log('No'); + return; + } + } - console.log('Yes'); + console.log('Yes'); } -let magazine = [ 'give', 'me', 'one', 'grand', 'today', 'night' ]; -let note = [ 'give', 'one', 'grand', 'today' ]; +const magazine = ['give', 'me', 'one', 'grand', 'today', 'night']; +const note = ['give', 'one', 'grand', 'today']; console.time('Time Taken'); checkMagazine(magazine, note); diff --git a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js index 138f0db..8b655d9 100644 --- a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js +++ b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js @@ -5,23 +5,23 @@ Link: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ */ function sherlockAndAnagrams(s) { - let count = 0; - let strLength = s.length; //get length - for (let i = 1; i < strLength; i++) { - let found = {}; - for (let j = 0; j + i <= strLength; j++) { - let substr = s.substr(j, i); //device string into substr - substr = substr.split('').sort().join(''); //sort it - if (found[substr]) { - count += found[substr]; //count total - found[substr]++; - } else { - found[substr] = 1; - } - } - } + let count = 0; + const strLength = s.length; // get length + for (let i = 1; i < strLength; i++) { + const found = {}; + for (let j = 0; j + i <= strLength; j++) { + let substr = s.substr(j, i); // device string into substr + substr = substr.split('').sort().join(''); // sort it + if (found[substr]) { + count += found[substr]; // count total + found[substr]++; + } else { + found[substr] = 1; + } + } + } - return count; + return count; } console.log(sherlockAndAnagrams('cdcd')); diff --git a/src/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js index f9f7e3d..cc1845d 100644 --- a/src/Dictionaries and Hashmaps/two-strings.js +++ b/src/Dictionaries and Hashmaps/two-strings.js @@ -6,22 +6,21 @@ */ function twoStrings(s1, s2) { - m = new Map(); - for(let i=0; i { - if (grade < 38) { - return grade; - } +module.exports = function gradingStudents(grades) { + const newGrades = grades.map((grade) => { + if (grade < 38) { + return grade; + } - let roundRemainder = grade % 5; + const roundRemainder = grade % 5; - if (roundRemainder === 0 || roundRemainder <= 2) { - return grade; - } + if (roundRemainder === 0 || roundRemainder <= 2) { + return grade; + } - return grade + (5 - roundRemainder); - }) + return grade + (5 - roundRemainder); + }); - return newGrades; - -} + return newGrades; +}; diff --git a/src/Numbers/kangaroo.js b/src/Numbers/kangaroo.js index 06495a1..780d34a 100644 --- a/src/Numbers/kangaroo.js +++ b/src/Numbers/kangaroo.js @@ -7,29 +7,26 @@ // Solution 1 function kangaroo(x1, v1, x2, v2) { - if ((x2 > x1 && v2 > v1) || v1 === v2) { - return 'NO'; - } + if ((x2 > x1 && v2 > v1) || v1 === v2) { + return 'NO'; + } - let x1Distance = x1; - let x2Distance = x2; + let x1Distance = x1; + let x2Distance = x2; - while (x1Distance !== x2Distance) { - x1Distance += v1; - x2Distance += v2; + while (x1Distance !== x2Distance) { + x1Distance += v1; + x2Distance += v2; - if (x1Distance > x2Distance) { - return 'NO'; - } - } - - return 'YES'; + if (x1Distance > x2Distance) { + return 'NO'; + } + } + return 'YES'; } - -//Solution 2 - +// Solution 2 /* @@ -46,11 +43,13 @@ x1 - x2 / v2 - v1 = y so we can find y with all 4 inputs if it is integer and greater than 0 then both will meet */ -function kangaroo(x1, v1, x2, v2) { - if (x2 > x1 && v2 > v1) { - return 'NO' - } +function kangarooSolution2(x1, v1, x2, v2) { + if (x2 > x1 && v2 > v1) { + return 'NO'; + } - let steps = (x1 - x2) % (v2 - v1); - return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; + const steps = (x1 - x2) % (v2 - v1); + return steps >= 0 && Number.isInteger(steps) ? 'YES' : 'NO'; } + +module.exports = [kangaroo, kangarooSolution2]; diff --git a/src/Numbers/plus-minus.js b/src/Numbers/plus-minus.js index b754238..164be6c 100644 --- a/src/Numbers/plus-minus.js +++ b/src/Numbers/plus-minus.js @@ -6,22 +6,22 @@ */ module.exports = function plusMinus(arr) { - let result = { - positive: 0, - negative: 0, - zero: 0, - } + const result = { + positive: 0, + negative: 0, + zero: 0, + }; - let arrLength = arr.length; - for (let index = 0; index < arrLength; index++){ - if (arr[index] === 0) { - ++result.zero; - } else if (arr[index] > 0) { - ++result.positive; - } else { - ++result.negative; - } - } + const arrLength = arr.length; + for (let index = 0; index < arrLength; index++) { + if (arr[index] === 0) { + ++result.zero; + } else if (arr[index] > 0) { + ++result.positive; + } else { + ++result.negative; + } + } - return result; -} + return result; +}; diff --git a/src/Numbers/staircase.js b/src/Numbers/staircase.js index f09ff35..6a05c07 100644 --- a/src/Numbers/staircase.js +++ b/src/Numbers/staircase.js @@ -6,10 +6,10 @@ */ function staircase(n) { - let tmp = n; - for (let index = 0; index < n; index++){ - console.log(' '.repeat(--tmp) + '#'.repeat(index + 1 )); - } + let tmp = n; + for (let index = 0; index < n; index++) { + console.log(' '.repeat(--tmp) + '#'.repeat(index + 1)); + } } staircase(6); diff --git a/src/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js index d6d9c81..794c249 100644 --- a/src/Sorting/bubble-sort.js +++ b/src/Sorting/bubble-sort.js @@ -6,22 +6,22 @@ */ function countSwaps(a) { - let isSorted = false; - let counter = 0; - while (!isSorted) { - isSorted = true; - for (let i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - [a[i], a[i + 1]] = [a[i + 1], a[i]]; - counter++; - isSorted = false; - } - } - } + let isSorted = false; + let counter = 0; + while (!isSorted) { + isSorted = true; + for (let i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + [a[i], a[i + 1]] = [a[i + 1], a[i]]; + counter++; + isSorted = false; + } + } + } - console.log(`Array is sorted in ${counter} swaps.`); - console.log(`First Element: ${a[0]}`); - console.log(`Last Element: ${a[a.length -1 ]}`); + console.log(`Array is sorted in ${counter} swaps.`); + console.log(`First Element: ${a[0]}`); + console.log(`Last Element: ${a[a.length - 1]}`); } countSwaps([5, 2, 1]); diff --git a/src/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js index cabb6db..80dcd98 100644 --- a/src/Sorting/mark-and-toys.js +++ b/src/Sorting/mark-and-toys.js @@ -6,20 +6,23 @@ */ function maximumToys(prices, balance) { - prices = prices.sort((a, b) => a - b) - let toysBought = 0; - console.log(prices); - for (let i = 0; i < prices.length; i++){ - if (balance >= prices[i]) { - toysBought++; - balance -= prices[i]; - } else { - break; - } - } - return toysBought; - + prices = prices.sort((a, b) => a - b); + let toysBought = 0; + console.log(prices); + for (let i = 0; i < prices.length; i++) { + if (balance >= prices[i]) { + toysBought++; + balance -= prices[i]; + } else { + break; + } + } + return toysBought; } -let arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; +const arr = [ + 33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, + 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, + 65846182, 8470661, 13597655, 360, +]; console.log(maximumToys(arr, 100000)); diff --git a/src/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js index 83bde36..79d6224 100644 --- a/src/Sorting/mini-max-sum.js +++ b/src/Sorting/mini-max-sum.js @@ -6,14 +6,14 @@ */ function miniMaxSum(arr) { - let sum = [0, 0]; - arr = arr.sort((a, b) => { return a - b }); - for (let i = 0; i < 4; i++){ - sum[0] += arr[i]; - sum[1] += arr[arr.length - (i+1)]; - } + const sum = [0, 0]; + arr = arr.sort((a, b) => a - b); + for (let i = 0; i < 4; i++) { + sum[0] += arr[i]; + sum[1] += arr[arr.length - (i + 1)]; + } - console.log(sum[0], sum[1]); + console.log(sum[0], sum[1]); } miniMaxSum(1, 2, 3, 4, 5); diff --git a/src/Strings/alternating-characters.js b/src/Strings/alternating-characters.js index b02de77..3fbcb1a 100644 --- a/src/Strings/alternating-characters.js +++ b/src/Strings/alternating-characters.js @@ -6,22 +6,22 @@ */ function alternatingCharacters(string) { - let prev = ''; - let counter = 0; - for (let index = 0; index < string.length; index++) { - if(!prev){ - prev = string[index]; - continue; - } + let prev = ''; + let counter = 0; + for (let index = 0; index < string.length; index++) { + if (!prev) { + prev = string[index]; + continue; + } - if(prev === string[index]){ - counter++; - } + if (prev === string[index]) { + counter++; + } - prev = string[index]; - } + prev = string[index]; + } - return counter; + return counter; } console.log(alternatingCharacters('BBBBB')); diff --git a/src/Strings/counting-valleys.js b/src/Strings/counting-valleys.js index dbb44ae..b8c21eb 100644 --- a/src/Strings/counting-valleys.js +++ b/src/Strings/counting-valleys.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/counting-valleys */ -function countingValleys(n, s) { - let currentValley = 0; - let count = 0; - for (let i = 0; i < n; i++) { +module.exports = function countingValleys(n, s) { + let currentValley = 0; + let count = 0; + for (let i = 0; i < n; i++) { + if (s[i] === 'U') { + currentValley++; + } + if (s[i] === 'D') { + currentValley--; + } - if (s[i] === 'U') { - currentValley++; - } - if (s[i] === 'D') { - currentValley--; - } + if (currentValley === 0 && s[i] === 'U') { + count++; + } + } - if (currentValley == 0 && s[i] === 'U') { - count++; - } - } - - return count; - -} + return count; +}; diff --git a/src/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js index 1e8ebbd..2564590 100644 --- a/src/Strings/hackerrank-in-string.js +++ b/src/Strings/hackerrank-in-string.js @@ -6,12 +6,12 @@ */ module.exports = function hackerrankInString(s) { - const mask = Array.from("hackerrank"); - for (let i = 0; i < s.length; i++) { - const currentChar = s.charAt(i); - if (mask[0] === currentChar) { - mask.shift(); - } - } - return mask.length === 0 ? "YES" : "NO"; + const mask = Array.from('hackerrank'); + for (let i = 0; i < s.length; i++) { + const currentChar = s.charAt(i); + if (mask[0] === currentChar) { + mask.shift(); + } + } + return mask.length === 0 ? 'YES' : 'NO'; }; diff --git a/src/Strings/making-anagrams.js b/src/Strings/making-anagrams.js index 4de1579..3fb1d88 100644 --- a/src/Strings/making-anagrams.js +++ b/src/Strings/making-anagrams.js @@ -4,47 +4,44 @@ Score: 25/ Link: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_r=internal-search */ - - -function makeAnagram(string1, string2){ - string1 = count(string1); - string2 = count(string2); - return findDiff(string1, string2); -} - function count(a) { - let arr = a.split('').sort(); - let counter = {}; - arr.forEach(value => { - if (counter[value] !== undefined) { - counter[value] += 1; - } else { - counter[value] = 1; - } - }) - - return counter; + const arr = a.split('').sort(); + const counter = {}; + arr.forEach((value) => { + if (counter[value] !== undefined) { + counter[value] += 1; + } else { + counter[value] = 1; + } + }); + + return counter; } function findDiff(arr1, arr2) { - let removeCount = 0; - - for (let key in arr1) { - if (!arr2[key]) { - removeCount += arr1[key]; - } else { - removeCount += Math.abs(arr2[key] - arr1[key]); - } - } - - for (let key in arr2) { - if (!arr1[key]) { - removeCount += arr2[key]; - } - } - return removeCount; + let removeCount = 0; + + for (const key in arr1) { + if (!arr2[key]) { + removeCount += arr1[key]; + } else { + removeCount += Math.abs(arr2[key] - arr1[key]); + } + } + + for (const key in arr2) { + if (!arr1[key]) { + removeCount += arr2[key]; + } + } + return removeCount; } -let a = "fcrxzwscanmligyxyvym"; -let b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; -console.log(makeAnagram(a,b )); +function makeAnagram(string1, string2) { + string1 = count(string1); + string2 = count(string2); + return findDiff(string1, string2); +} +const a = 'fcrxzwscanmligyxyvym'; +const b = 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'; +console.log(makeAnagram(a, b)); diff --git a/src/Strings/repeated-string.js b/src/Strings/repeated-string.js index 4497df6..6e71159 100644 --- a/src/Strings/repeated-string.js +++ b/src/Strings/repeated-string.js @@ -6,11 +6,11 @@ */ module.exports = function repeatedString(s, n) { - let initialCount = s.split('a').length - 1; - let cocent = Math.floor(n / s.length); - let total = cocent * initialCount; - let remainder = n % s.length; - let remaindLetter = s.slice(0, remainder); - total += remaindLetter.split('a').length - 1; - return total; -} + const initialCount = s.split('a').length - 1; + const cocent = Math.floor(n / s.length); + let total = cocent * initialCount; + const remainder = n % s.length; + const remaindLetter = s.slice(0, remainder); + total += remaindLetter.split('a').length - 1; + return total; +}; diff --git a/src/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js index 5846fcf..6b4a1cc 100644 --- a/src/Strings/sherlock-and-the-valid-string.js +++ b/src/Strings/sherlock-and-the-valid-string.js @@ -6,36 +6,35 @@ */ function isValid(string) { - let counter = {}; - - let arr = string.split('').sort(); - let smallValue = 0; - let allowedTimes = 0; - arr.forEach(element => { - counter[element] = counter[element] === undefined ? 1 : counter[element]+1; - }); - - for(let key in counter){ - if(smallValue === 0){ - smallValue = counter[key]; - continue ; - } - - if(smallValue !== counter[key]){ - if(counter[key] === 1){ - allowedTimes += 1; - } else { - allowedTimes += Math.abs(smallValue - counter[key]); - } - } - - if(allowedTimes > 1){ - break; - } - } - - return allowedTimes > 1 ? false : true; + const counter = {}; + + const arr = string.split('').sort(); + let smallValue = 0; + let allowedTimes = 0; + arr.forEach((element) => { + counter[element] = counter[element] === undefined ? 1 : counter[element] + 1; + }); + + for (const key in counter) { + if (smallValue === 0) { + smallValue = counter[key]; + continue; + } + + if (smallValue !== counter[key]) { + if (counter[key] === 1) { + allowedTimes += 1; + } else { + allowedTimes += Math.abs(smallValue - counter[key]); + } + } + + if (allowedTimes > 1) { + break; + } + } + + return !(allowedTimes > 1); } - -console.log(isValid("abcdefghhgfedecba")); +console.log(isValid('abcdefghhgfedecba')); diff --git a/src/Strings/strong-password.js b/src/Strings/strong-password.js index d3fd7c0..fa54fb6 100644 --- a/src/Strings/strong-password.js +++ b/src/Strings/strong-password.js @@ -6,27 +6,21 @@ */ module.exports = function passwordStrengthMinimumNumber(n, password) { - const STRONG_LENGTH = 6; - const missingChars = STRONG_LENGTH - n; - let score = 0; + const STRONG_LENGTH = 6; + const missingChars = STRONG_LENGTH - n; + let score = 0; - const passwordAsArray = Array.from(password); + const passwordAsArray = Array.from(password); - const hasNumber = passwordAsArray.some(char => "0123456789".includes(char)); - const hasLowerCase = passwordAsArray.some(char => - "abcdefghijklmnopqrstuvwxyz".includes(char) - ); - const hasUpperCase = passwordAsArray.some(char => - "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(char) - ); - const hasSpecialChar = passwordAsArray.some(char => - "!@#$%^&*()-+".includes(char) - ); + const hasNumber = passwordAsArray.some((char) => '0123456789'.includes(char)); + const hasLowerCase = passwordAsArray.some((char) => 'abcdefghijklmnopqrstuvwxyz'.includes(char)); + const hasUpperCase = passwordAsArray.some((char) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(char)); + const hasSpecialChar = passwordAsArray.some((char) => '!@#$%^&*()-+'.includes(char)); - if (!hasNumber) score++; - if (!hasLowerCase) score++; - if (!hasUpperCase) score++; - if (!hasSpecialChar) score++; + if (!hasNumber) score++; + if (!hasLowerCase) score++; + if (!hasUpperCase) score++; + if (!hasSpecialChar) score++; - return Math.max(score, missingChars); + return Math.max(score, missingChars); }; diff --git a/src/Strings/time-conversion.js b/src/Strings/time-conversion.js index 6cabfbc..dc86243 100644 --- a/src/Strings/time-conversion.js +++ b/src/Strings/time-conversion.js @@ -5,24 +5,23 @@ Link: https://www.hackerrank.com/challenges/time-conversion/ */ - module.exports = function timeConversion(time) { - let cycle = time.substring(time.length - 2, time.length); - let timeWithoutCycle = time.substring(0, time.length - 2); - let timeArr = timeWithoutCycle.split(':'); + const cycle = time.substring(time.length - 2, time.length); + const timeWithoutCycle = time.substring(0, time.length - 2); + const timeArr = timeWithoutCycle.split(':'); - if (cycle === 'AM') { - if (timeArr[0] != 12) { - return timeWithoutCycle; - } + if (cycle === 'AM') { + if (timeArr[0] !== '12') { + return timeWithoutCycle; + } - timeArr[0] = '00'; - return timeArr.join(':'); - } + timeArr[0] = '00'; + return timeArr.join(':'); + } - if (timeArr[0] != 12) { - timeArr[0] = parseInt(timeArr[0]) + 12; - } + if (timeArr[0] !== '12') { + timeArr[0] = parseInt(timeArr[0], 10) + 12; + } - return timeArr.join(':') -} + return timeArr.join(':'); +}; From e4d684ad32c585a0e7fb6e00e0207dc8529ca291 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Thu, 28 Oct 2021 00:56:38 +0530 Subject: [PATCH 3/8] Revert "Fix eslint and add eslint to travis" This reverts commit 16b1b2e457577e9119fc457f71a6e08f1d96e716. --- .editorconfig | 4 +- .eslintrc.json | 55 ++++++------- .travis.yml | 4 +- package.json | 12 +-- src/Arrays/2d-array-ds.js | 28 +++---- src/Arrays/apple-and-orange.js | 28 ++++--- src/Arrays/array-manipulation.js | 18 ++-- src/Arrays/birthday-cake-candles.js | 24 +++--- src/Arrays/breaking-best-and-worst-records.js | 62 +++++++------- src/Arrays/compare-the-triplets.js | 20 ++--- src/Arrays/diagonal-difference.js | 25 +++--- src/Arrays/jumping-on-the-clouds.js | 31 +++---- src/Arrays/left-rotation.js | 17 ++-- src/Arrays/minimum-swaps-2.js | 35 ++++---- src/Arrays/newyear-chaos.js | 36 ++++---- src/Arrays/sock-merchant.js | 36 ++++---- src/Data Structures/cycle-detection.js | 41 +++++----- .../reverse-doubly-linked-list.js | 82 ++++++++++--------- .../count-triplet.js | 37 +++++---- .../custom-hashmap.js | 40 ++++----- .../frequency-queries.js | 58 ++++++------- .../game-of-thrones.js | 16 ++-- src/Dictionaries and Hashmaps/ransom-note.js | 71 ++++++++-------- .../sherlock-and-anagrams.js | 32 ++++---- src/Dictionaries and Hashmaps/two-strings.js | 25 +++--- src/Numbers/grading.js | 27 +++--- src/Numbers/kangaroo.js | 45 +++++----- src/Numbers/plus-minus.js | 34 ++++---- src/Numbers/staircase.js | 8 +- src/Sorting/bubble-sort.js | 30 +++---- src/Sorting/mark-and-toys.js | 31 ++++--- src/Sorting/mini-max-sum.js | 14 ++-- src/Strings/alternating-characters.js | 26 +++--- src/Strings/counting-valleys.js | 34 ++++---- src/Strings/hackerrank-in-string.js | 16 ++-- src/Strings/making-anagrams.js | 73 +++++++++-------- src/Strings/repeated-string.js | 16 ++-- src/Strings/sherlock-and-the-valid-string.js | 61 +++++++------- src/Strings/strong-password.js | 32 +++++--- src/Strings/time-conversion.js | 31 +++---- 40 files changed, 663 insertions(+), 652 deletions(-) diff --git a/.editorconfig b/.editorconfig index 3281cce..1a6d62e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,9 +6,9 @@ end_of_line = lf indent_size = 2 indent_style = tab insert_final_newline = true -max_line_length = 155 +max_line_length = 130 trim_trailing_whitespace = true [*.md] -max_line_length = 155 +max_line_length = 130 trim_trailing_whitespace = true diff --git a/.eslintrc.json b/.eslintrc.json index a9d94b6..fd4d4cf 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,30 +1,27 @@ { - "env": { - "browser": true, - "commonjs": true, - "es2021": true - }, - "extends": ["eslint:recommended", "airbnb-base"], - "parserOptions": { - "ecmaVersion": 12 - }, - "rules": { - "indent": ["error", "tab"], - "no-tabs": ["warn", { "allowIndentationTabs": true }], - "max-len": ["error", { "code": 155 }], - "no-var": "error", - "semi": "error", - "no-multi-spaces": "error", - "space-in-parens": "error", - "no-multiple-empty-lines": "error", - "prefer-const": "error", - "no-use-before-define": "error", - "max-classes-per-file": ["warn", 1], - "no-plusplus": "off", - "no-param-reassign": "warn", - "no-restricted-syntax": "warn", - "no-continue": "warn", - "no-bitwise": "off", - "guard-for-in": "warn" - } -} + "env": { + "browser": true, + "commonjs": true, + "es2021": true + }, + "extends": [ + "eslint:recommended", + "airbnb-base" + ], + "parserOptions": { + "ecmaVersion": 12 + }, + "rules": { + "indent": ["error", "tab"], + "no-tabs": ["error", { "allowIndentationTabs": true }], + "max-len": ["error", { "code": 130 }], + "no-var": "error", + "semi": "error", + "no-multi-spaces": "error", + "space-in-parens": "error", + "no-multiple-empty-lines": "error", + "prefer-const": "error", + "no-use-before-define": "error" + } + } + diff --git a/.travis.yml b/.travis.yml index 437f211..9ef231a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,5 +5,5 @@ node_js: install: - npm install script: - - npm run test - - eslint src test --ext .js +- npm run test +- npm run lint diff --git a/package.json b/package.json index c819338..f9db512 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,11 @@ "version": "1.0.0", "description": "Solutions for HackerRank Problems in Javascript.", "main": "index.js", - "nyc": { - "all": true, - "include": [ - "src/**/*.js" - ] - }, "scripts": { - "test": "nyc mocha --recursive", - "prepare": "husky install" + "test": "mocha --recursive", + "report": "nyc mocha --recursive", + "prepare": "husky install", + "lint": "prettier --write **/*.*js && eslint --fix " }, "lint-staged": { "*.js": [ diff --git a/src/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js index 398f4fd..1e5a28e 100644 --- a/src/Arrays/2d-array-ds.js +++ b/src/Arrays/2d-array-ds.js @@ -4,20 +4,14 @@ Score: 15 Link: https://www.hackerrank.com/challenges/2d-array/ */ -module.exports = function hourglassSum(arr) { - let sum = -1000; - let max = sum; - for (let i = 0; i < 4; i++) { - for (let j = 0; j < 4; j++) { - sum = arr[i][j] - + arr[i][j + 1] - + arr[i][j + 2] - + arr[i + 1][j + 1] - + arr[i + 2][j] - + arr[i + 2][j + 1] - + arr[i + 2][j + 2]; - if (sum > max) max = sum; - } - } - console.log(max); -}; +function hourglassSum(arr) { + var sum = -1000 + let max = sum + for(let i = 0 ; i<4;i++){ + for(let j = 0 ; j<4; j++){ + sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] + if(sum>max) max = sum + } + } + console.log(max) +} diff --git a/src/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js index 3aea64e..ffaf16a 100644 --- a/src/Arrays/apple-and-orange.js +++ b/src/Arrays/apple-and-orange.js @@ -4,21 +4,23 @@ Score: 10 Link: https://www.hackerrank.com/challenges/apple-and-orange */ -function countFruitsFallInsideHome(fruits, startHome, EndHome) { - let counter = 0; - fruits.forEach((fruit) => { - if (fruit >= startHome && fruit <= EndHome) { - counter++; - } - return counter; - }); - return console.log(counter); +function countApplesAndOranges(s, t, a, b, apples, oranges) { + countFruitsFallInsideHome(apples, s - a, t - a); + countFruitsFallInsideHome(oranges, s - b, t - b); } -function countApplesAndOranges(s, t, a, b, apples, oranges) { - countFruitsFallInsideHome(apples, s - a, t - a); - countFruitsFallInsideHome(oranges, s - b, t - b); + +function countFruitsFallInsideHome(fruits, startHome, EndHome) { + let counter = 0; + fruits.forEach(fruit => { + if (fruit >= startHome && fruit <= EndHome) { + return counter++; + } + }); + + return console.log(counter); } -countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1], [5 - 6]); +countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1] , [5 -6]); + diff --git a/src/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js index a04ae2b..45eaf1d 100644 --- a/src/Arrays/array-manipulation.js +++ b/src/Arrays/array-manipulation.js @@ -5,14 +5,14 @@ Link: https://www.hackerrank.com/challenges/crush/problem */ -module.exports = function arrayManipulation(n, queries) { - const arr = Array(n).fill(0); +function arrayManipulation(n, queries) { + let arr = Array(n).fill(0); - for (let a = 0; a < queries.length; a++) { - for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { - arr[index] += queries[a][2]; - } - } + for (let a = 0; a < queries.length; a++) { + for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { + arr[index] += queries[a][2]; + } + } - return Math.max(...arr); -}; + return Math.max(...arr); +} diff --git a/src/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js index 674311e..35ed0d7 100644 --- a/src/Arrays/birthday-cake-candles.js +++ b/src/Arrays/birthday-cake-candles.js @@ -6,16 +6,16 @@ */ module.exports = function birthdayCakeCandles(arr) { - let tallestCandle = 0; - let candlesCounter = 0; - for (let index = 0; index < arr.length; index++) { - if (arr[index] > tallestCandle) { - tallestCandle = arr[index]; - candlesCounter = 1; - } else if (arr[index] === tallestCandle) { - candlesCounter++; - } - } + let tallestCandle = 0; + let candlesCounter = 0; + for (let index = 0; index < arr.length; index++) { + if (arr[index] > tallestCandle) { + tallestCandle = arr[index]; + candlesCounter = 1; + } else if (arr[index] === tallestCandle) { + candlesCounter++; + } + } - return candlesCounter; -}; + return candlesCounter; +} diff --git a/src/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js index 9df7f33..1afad77 100644 --- a/src/Arrays/breaking-best-and-worst-records.js +++ b/src/Arrays/breaking-best-and-worst-records.js @@ -6,35 +6,37 @@ */ function breakingRecords(scores) { - const counters = { - min: 0, - max: 0, - }; - - const values = { - min: 0, - max: 0, - }; - let isDefaultSet = false; - - scores.forEach((score) => { - if (!isDefaultSet) { - values.min = score; - values.max = score; - isDefaultSet = true; - return; - } - - if (score > values.max) { - values.max = score; - counters.max++; - } else if (score < values.min) { - values.min = score; - counters.min++; - } - }); - - return [counters.max, counters.min]; + + let counters = { + min: 0, + max: 0 + }; + + let values = { + min: 0, + max: 0 + } + let isDefaultSet = false; + + scores.forEach(score => { + if (!isDefaultSet) { + values.min = score; + values.max = score; + isDefaultSet = true; + return ; + } + + if (score > values.max) { + values.max = score; + counters.max++; + } else if (score < values.min) { + values.min = score; + counters.min++; + } + }) + + return [counters.max, counters.min]; + } -breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]); +breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]) diff --git a/src/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js index b542423..75d6007 100644 --- a/src/Arrays/compare-the-triplets.js +++ b/src/Arrays/compare-the-triplets.js @@ -6,16 +6,16 @@ Link: https://www.hackerrank.com/challenges/compare-the-triplets/problem */ function compareTriplets(a, b) { - const points = [0, 0]; - for (let index = 0; index < a.length; index++) { - if (a[index] > b[index]) { - points[0] += 1; - } else if (a[index] < b[index]) { - points[1] += 1; - } - } + let points = [0, 0]; + for (let index = 0; index < a.length; index++){ + if (a[index] > b[index]) { + points[0] += 1; + } else if (a[index] < b[index]) { + points[1] += 1; + } + } - return points; + return points; } -console.log(compareTriplets([5, 6, 7], [3, 6, 10])); +console.log(compareTriplets([5, 6, 7], [3, 6, 10])) diff --git a/src/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js index a8290c3..336b05d 100644 --- a/src/Arrays/diagonal-difference.js +++ b/src/Arrays/diagonal-difference.js @@ -1,3 +1,4 @@ + /* Title:Diagonal Difference Difficulty: Easy @@ -6,20 +7,16 @@ */ function diagonalDifference(arr) { - let leftToRight = 0; - let rightToLeft = 0; - let tmpLength = arr.length; - for (let i = 0; i < arr.length; i++) { - leftToRight += arr[i][i]; - rightToLeft += arr[i][--tmpLength]; - } + let leftToRight = 0; + let rightToLeft = 0; + let tmpLength = arr.length; + for (let i = 0; i < arr.length; i++){ + leftToRight += arr[i][i]; + rightToLeft += arr[i][--tmpLength]; + } - return Math.abs(leftToRight - rightToLeft); + return Math.abs(leftToRight - rightToLeft); } -const input = [ - [11, 2, 4], - [4, 5, 6], - [10, 8, -12], -]; -console.log(diagonalDifference(input)); +let input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] +console.log(diagonalDifference(input)) diff --git a/src/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js index 0488a2f..9f5c7d1 100644 --- a/src/Arrays/jumping-on-the-clouds.js +++ b/src/Arrays/jumping-on-the-clouds.js @@ -5,19 +5,20 @@ Link: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ */ -module.exports = function jumpingOnClouds(c) { - let jump = 0; - for (let i = 0; i < c.length;) { - if (c[i + 2] === 0) { - jump++; - i += 2; - } else if (c[i + 1] === 0) { - jump++; - i += 1; - } else { - i++; - } - } +function jumpingOnClouds(c) { - return jump; -}; + let jump = 0; + for (let i = 0; i < c.length;){ + if (c[i + 2] == 0) { + jump++; + i += 2; + } else if (c[i + 1] == 0) { + jump++; + i += 1; + } else { + i++; + } + } + + return jump; +} diff --git a/src/Arrays/left-rotation.js b/src/Arrays/left-rotation.js index 7881ba7..17ed7de 100644 --- a/src/Arrays/left-rotation.js +++ b/src/Arrays/left-rotation.js @@ -6,13 +6,14 @@ */ module.exports = function rotLeft(a, d) { - if (!a.length) { - return []; - } - for (let i = 0; i < d; i++) { - a.push(a.shift()); - } + if(!a.length){ + return [] + } - return a; -}; + for (let i = 0; i < d; i++) { + a.push(a.shift()); + } + + return a; +} diff --git a/src/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js index 95c93fc..c382556 100644 --- a/src/Arrays/minimum-swaps-2.js +++ b/src/Arrays/minimum-swaps-2.js @@ -5,21 +5,22 @@ Link: https://www.hackerrank.com/challenges/minimum-swaps-2 */ -module.exports = function minimumSwaps(arr) { - const origArray = arr.slice(0); - const sortedArray = arr.sort((a, b) => a - b); - let numberOfSwap = 0; - for (let i = 0; i < origArray.length; i++) { - if (origArray[i] !== sortedArray[i]) { - for (let j = i + 1; j < origArray.length; j++) { - if (origArray[j] === sortedArray[i]) { - [origArray[i], origArray[j]] = [origArray[j], origArray[i]]; - numberOfSwap++; - break; - } - } - } - } - return numberOfSwap; -}; +function minimumSwaps(arr) { + var origArray = arr.slice(0); + var sortedArray = arr.sort((a,b) => a-b); + let numberOfSwap = 0; + for (var i = 0; i < origArray.length; i++) { + if (origArray[i] != sortedArray[i]) { + for (var j = i + 1; j < origArray.length; j++) { + if (origArray[j] === sortedArray[i]) { + [origArray[i], origArray[j]] = [origArray[j], origArray[i]] + numberOfSwap++ + break; + } + } + } + } + + return numberOfSwap; +} diff --git a/src/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js index e9a022f..0ae6270 100644 --- a/src/Arrays/newyear-chaos.js +++ b/src/Arrays/newyear-chaos.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/new-year-chaos/ */ -module.exports = function minimumBribes(q) { - let swaps = 0; - let min = q.length; - for (let i = q.length - 1; i >= 0; i--) { - if (q[i] - i > 3) { - return 'Too chaotic'; - } - if (q[i] > i + 1) { - swaps += q[i] - (i + 1); - } else if (min > q[i]) { - min = q[i]; - } else if (q[i] !== min) { - swaps++; - } - } +function minimumBribes(q) { + let swaps = 0; + let min = q.length; + for (var i = q.length -1 ; i >= 0; i--) { + if (q[i] - i > 3) { + return `Too chaotic`; + } + if (q[i] > i + 1) { + swaps += (q[i] - (i + 1)); + } else { + if (min > q[i]) { + min = q[i]; + } else if (q[i] != min) { + swaps++; + } + } + } - return swaps; -}; + return swaps; +} diff --git a/src/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js index c75cf50..e865834 100644 --- a/src/Arrays/sock-merchant.js +++ b/src/Arrays/sock-merchant.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/sock-merchant */ -module.exports = function sockMerchant(n, ar) { - const tmpArr = []; - let counter = 0; - ar.map((value) => { - if (tmpArr.includes(value)) { - const index = tmpArr.indexOf(value); - if (index > -1) { - tmpArr.splice(index, 1); - } - counter++; - } else { - tmpArr.push(value); - } - return value; - }); - return counter; -}; +function sockMerchant(n, ar) { + let tmpArr = []; + let counter = 0; + ar.map(value => { + if (tmpArr.includes(value)) { + var index = tmpArr.indexOf(value); + if (index > -1) { + tmpArr.splice(index, 1); + } + counter++; + } else { + tmpArr.push(value); + } + + }) + + return counter; + +} diff --git a/src/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js index ed53bab..5bd280a 100644 --- a/src/Data Structures/cycle-detection.js +++ b/src/Data Structures/cycle-detection.js @@ -6,33 +6,30 @@ */ function hasCycle(head) { - if (head === null || head.next === null || head.next.next === null) { - return false; - } // edge cases - let hare = head; - let tortoise = head; - do { - hare = hare.next.next; // 'hare' moves twice per tick - tortoise = tortoise.next; // 'tortoise' moves once per tick - } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); - return hare === tortoise; + if (head === null || head.next === null || head.next.next === null) return false; // edge cases + let hare = head; + let tortoise = head; + do { + hare = hare.next.next; // 'hare' moves twice per tick + tortoise = tortoise.next; // 'tortoise' moves once per tick + } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); + return hare === tortoise; } // NODE CLASS class Node { - constructor(data) { - this.data = data; - this.next = null; - } - - insert(data) { - this.next = new Node(data); - return this.next; // for chaining - } + constructor (data) { + this.data = data; + this.next = null; + } + insert (data) { + this.next = new Node(data); + return this.next; // for chaining + } } module.exports = { - hasCycle, - Node, -}; + hasCycle, + Node, +}; \ No newline at end of file diff --git a/src/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js index 71a4f23..04dcde3 100644 --- a/src/Data Structures/reverse-doubly-linked-list.js +++ b/src/Data Structures/reverse-doubly-linked-list.js @@ -1,52 +1,56 @@ +'use strict'; /* Title: Reverse a doubly linked list Difficulty: Easy Score: 5 Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem */ -class DoublyLinkedListNode { - constructor(nodeData) { - this.data = nodeData; - this.next = null; - this.prev = null; - } + + +function reverse(head) { + while (head.next) { + head = head.next + } + + const newList = new DoublyLinkedList(); + + while (head) { + newList.insertNode(head.data); + head = head.prev + } + return newList.head } +class DoublyLinkedListNode { + constructor(nodeData) { + this.data = nodeData; + this.next = null; + this.prev = null; + } +}; + class DoublyLinkedList { - constructor() { - this.head = null; - this.tail = null; - } - - insertNode(nodeData) { - const node = new DoublyLinkedListNode(nodeData); - - if (this.head == null) { - this.head = node; - } else { - this.tail.next = node; - node.prev = this.tail; - } - - this.tail = node; - } -} + constructor() { + this.head = null; + this.tail = null; + } -function reverse(head) { - while (head.next) { - head = head.next; - } + insertNode(nodeData) { + let node = new DoublyLinkedListNode(nodeData); - const newList = new DoublyLinkedList(); + if (this.head == null) { + this.head = node; + } else { + this.tail.next = node; + node.prev = this.tail; + } - while (head) { - newList.insertNode(head.data); - head = head.prev; - } - return newList.head; -} -module.exports = { - reverse, - DoublyLinkedList, - DoublyLinkedListNode, + this.tail = node; + } }; + +module.exports = { + reverse, + DoublyLinkedList, + DoublyLinkedListNode +} diff --git a/src/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js index 38656ad..ac8d48c 100644 --- a/src/Dictionaries and Hashmaps/count-triplet.js +++ b/src/Dictionaries and Hashmaps/count-triplet.js @@ -6,29 +6,30 @@ */ function countTriplets(arr, r) { - const second = {}; - const third = {}; - let count = 0; - for (let index = 0; index < arr.length; index++) { - const val = arr[index]; + let second = {} + let third = {} + let count = 0; + for (let index = 0; index < arr.length; index++) { - // If value found on third then add it to count - if (third[val]) { - count += third[val]; - } + const val = arr[index]; - // If value found on second , convey it to third + //If value found on third then add it to count + if(third[val]){ + count += third[val]; + } - if (second[val]) { - third[val * r] = third[val * r] + second[val] || second[val]; - } + //If value found on second , convey it to third - // add current element into second value + if(second[val]){ + third[val*r] = third[val*r] + second[val] || second[val]; + } - second[val * r] = second[val * r] + 1 || 1; - } + //add current element into second value - return count; + second[val*r] = second[val*r]+1 || 1; + } + + return count; } -console.log(countTriplets([1, 2, 2, 4], 2)); +console.log(countTriplets([1,2 ,2,4], 2)); diff --git a/src/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js index f7a2fe6..c2431ec 100644 --- a/src/Dictionaries and Hashmaps/custom-hashmap.js +++ b/src/Dictionaries and Hashmaps/custom-hashmap.js @@ -5,31 +5,31 @@ Link: - */ class customHashMap { - constructor() { - this.list = []; - } + constructor() { + this.list = []; + } - get(x) { - return this.list[this.hashCode(x)]; - } + get(x) { + return this.list[this.hashCode(x)]; + } - set(x, y) { - this.list[this.hashCode(x)] = y; - } + set(x, y) { + this.list[this.hashCode(x)] = y; + } - static hashCode(str) { - let hash = 0; - if (str.length === 0) return hash; - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i); - hash = (hash << 5) - hash + char; - hash &= hash; // Convert to 32bit integer - } - return hash; - } + hashCode(str) { + let hash = 0; + if (str.length == 0) return hash; + for (let i = 0; i < str.length; i++) { + let char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash = hash & hash; // Convert to 32bit integer + } + return hash; + } } -const m = customHashMap(); +let m = new customHashMap(); m.set('hello', 'world'); console.log(m.get('hello')); diff --git a/src/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js index 40ccb6b..c3f4d5a 100644 --- a/src/Dictionaries and Hashmaps/frequency-queries.js +++ b/src/Dictionaries and Hashmaps/frequency-queries.js @@ -6,40 +6,40 @@ */ function freqQuery(arr) { - const result = []; - const hash = {}; - const freq = []; + const result = []; + const hash = {}; + const freq = []; - for (let i = 0; i < arr.length; i += 1) { - const [action, value] = arr[i]; - const initValue = hash[value] || 0; + for (let i = 0; i < arr.length; i += 1) { + const [action, value] = arr[i]; + const initValue = hash[value] || 0; - if (action === 1) { - hash[value] = initValue + 1; - freq[initValue] = (freq[initValue] || 0) - 1; - freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; - } + if (action === 1) { + hash[value] = initValue + 1; + freq[initValue] = (freq[initValue] || 0) - 1; + freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; + } - if (action === 2 && initValue > 0) { - hash[value] = initValue - 1; - freq[initValue - 1] += 1; - freq[initValue] -= 1; - } + if (action === 2 && initValue > 0) { + hash[value] = initValue - 1; + freq[initValue - 1] += 1; + freq[initValue] -= 1; + } - if (action === 3) result.push(freq[value] > 0 ? 1 : 0); - } + if (action === 3) result.push(freq[value] > 0 ? 1 : 0); + } - return result; + return result; } -const input = [ - [1, 5], - [1, 6], - [3, 2], - [1, 10], - [1, 10], - [1, 6], - [2, 5], - [3, 2], -]; +let input = [ + [1, 5], + [1, 6], + [3, 2], + [1, 10], + [1, 10], + [1, 6], + [2, 5], + [3, 2] + ]; console.log(freqQuery(input)); diff --git a/src/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js index d516d12..0d50f1e 100644 --- a/src/Dictionaries and Hashmaps/game-of-thrones.js +++ b/src/Dictionaries and Hashmaps/game-of-thrones.js @@ -6,14 +6,12 @@ */ function gameOfThrones(s) { - const frequencies = {}; - for (const char of s) frequencies[char] = frequencies[char] + 1 || 1; - const oddFrequencies = Object.values(frequencies).filter( - (frequency) => frequency % 2, - ); - return oddFrequencies.length <= 1 ? 'YES' : 'NO'; + const frequencies = {}; + for (let char of s) frequencies[char] = frequencies[char] + 1 || 1; + let oddFrequencies = Object.values(frequencies).filter(frequency => frequency % 2); + return oddFrequencies.length <= 1 ? 'YES' : 'NO'; } -console.log(gameOfThrones('aaabbbb')); // YES -console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO -console.log(gameOfThrones('cdcdcdcdeeeef')); // YES +console.log(gameOfThrones('aaabbbb')); // YES +console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO +console.log(gameOfThrones('cdcdcdcdeeeef')); // YES \ No newline at end of file diff --git a/src/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js index 2268c69..bf7003a 100644 --- a/src/Dictionaries and Hashmaps/ransom-note.js +++ b/src/Dictionaries and Hashmaps/ransom-note.js @@ -6,48 +6,51 @@ */ class ExtendedMap { - constructor() { - this.map = new Map(); - } - - get(x) { - let value = this.map.get(x); - if (value === 1) { - this.map.delete(x); - return true; - } - - return this.map.set(x, --value); - } - - set(x, y) { - if (this.map.get(x)) { - return this.map.set(x, this.map.get(x) + 1); - } - - return this.map.set(x, y); - } + + constructor(){ + this.map = new Map(); + } + + get(x) { + let value = this.map.get(x); + if (value === 1) { + this.map.delete(x); + return true; + } + + return this.map.set(x, --value); + } + + set(x, y) { + if (this.map.get(x)) { + return this.map.set(x, this.map.get(x) + 1); + } + + return this.map.set(x, y); + } } + function checkMagazine(magazine, note) { - const m = new ExtendedMap(); - for (let i = 0; i < magazine.length; i++) { - m.set(magazine[i], 1); - } + let m = new ExtendedMap() + + for (let i = 0; i < magazine.length; i++) { + m.set(magazine[i], 1) + } - for (let i = 0; i < note.length; i++) { - if (!m.get(note[i])) { - console.log('No'); - return; - } - } + for (let i = 0; i < note.length; i++) { + if (!m.get(note[i])) { + console.log('No'); + return; + }; + } - console.log('Yes'); + console.log('Yes'); } -const magazine = ['give', 'me', 'one', 'grand', 'today', 'night']; -const note = ['give', 'one', 'grand', 'today']; +let magazine = [ 'give', 'me', 'one', 'grand', 'today', 'night' ]; +let note = [ 'give', 'one', 'grand', 'today' ]; console.time('Time Taken'); checkMagazine(magazine, note); diff --git a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js index 8b655d9..138f0db 100644 --- a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js +++ b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js @@ -5,23 +5,23 @@ Link: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ */ function sherlockAndAnagrams(s) { - let count = 0; - const strLength = s.length; // get length - for (let i = 1; i < strLength; i++) { - const found = {}; - for (let j = 0; j + i <= strLength; j++) { - let substr = s.substr(j, i); // device string into substr - substr = substr.split('').sort().join(''); // sort it - if (found[substr]) { - count += found[substr]; // count total - found[substr]++; - } else { - found[substr] = 1; - } - } - } + let count = 0; + let strLength = s.length; //get length + for (let i = 1; i < strLength; i++) { + let found = {}; + for (let j = 0; j + i <= strLength; j++) { + let substr = s.substr(j, i); //device string into substr + substr = substr.split('').sort().join(''); //sort it + if (found[substr]) { + count += found[substr]; //count total + found[substr]++; + } else { + found[substr] = 1; + } + } + } - return count; + return count; } console.log(sherlockAndAnagrams('cdcd')); diff --git a/src/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js index cc1845d..f9f7e3d 100644 --- a/src/Dictionaries and Hashmaps/two-strings.js +++ b/src/Dictionaries and Hashmaps/two-strings.js @@ -6,21 +6,22 @@ */ function twoStrings(s1, s2) { - const m = new Map(); - for (let i = 0; i < s1.length; i++) { - m.set(s1[i], 1); - } + m = new Map(); + for(let i=0; i { - if (grade < 38) { - return grade; - } +function gradingStudents(grades) { + let newGrades = grades.map(grade => { + if (grade < 38) { + return grade; + } - const roundRemainder = grade % 5; + let roundRemainder = grade % 5; - if (roundRemainder === 0 || roundRemainder <= 2) { - return grade; - } + if (roundRemainder === 0 || roundRemainder <= 2) { + return grade; + } - return grade + (5 - roundRemainder); - }); + return grade + (5 - roundRemainder); + }) - return newGrades; -}; + return newGrades; + +} diff --git a/src/Numbers/kangaroo.js b/src/Numbers/kangaroo.js index 780d34a..06495a1 100644 --- a/src/Numbers/kangaroo.js +++ b/src/Numbers/kangaroo.js @@ -7,26 +7,29 @@ // Solution 1 function kangaroo(x1, v1, x2, v2) { - if ((x2 > x1 && v2 > v1) || v1 === v2) { - return 'NO'; - } + if ((x2 > x1 && v2 > v1) || v1 === v2) { + return 'NO'; + } - let x1Distance = x1; - let x2Distance = x2; + let x1Distance = x1; + let x2Distance = x2; - while (x1Distance !== x2Distance) { - x1Distance += v1; - x2Distance += v2; + while (x1Distance !== x2Distance) { + x1Distance += v1; + x2Distance += v2; - if (x1Distance > x2Distance) { - return 'NO'; - } - } + if (x1Distance > x2Distance) { + return 'NO'; + } + } + + return 'YES'; - return 'YES'; } -// Solution 2 + +//Solution 2 + /* @@ -43,13 +46,11 @@ x1 - x2 / v2 - v1 = y so we can find y with all 4 inputs if it is integer and greater than 0 then both will meet */ -function kangarooSolution2(x1, v1, x2, v2) { - if (x2 > x1 && v2 > v1) { - return 'NO'; - } +function kangaroo(x1, v1, x2, v2) { + if (x2 > x1 && v2 > v1) { + return 'NO' + } - const steps = (x1 - x2) % (v2 - v1); - return steps >= 0 && Number.isInteger(steps) ? 'YES' : 'NO'; + let steps = (x1 - x2) % (v2 - v1); + return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; } - -module.exports = [kangaroo, kangarooSolution2]; diff --git a/src/Numbers/plus-minus.js b/src/Numbers/plus-minus.js index 164be6c..b754238 100644 --- a/src/Numbers/plus-minus.js +++ b/src/Numbers/plus-minus.js @@ -6,22 +6,22 @@ */ module.exports = function plusMinus(arr) { - const result = { - positive: 0, - negative: 0, - zero: 0, - }; + let result = { + positive: 0, + negative: 0, + zero: 0, + } - const arrLength = arr.length; - for (let index = 0; index < arrLength; index++) { - if (arr[index] === 0) { - ++result.zero; - } else if (arr[index] > 0) { - ++result.positive; - } else { - ++result.negative; - } - } + let arrLength = arr.length; + for (let index = 0; index < arrLength; index++){ + if (arr[index] === 0) { + ++result.zero; + } else if (arr[index] > 0) { + ++result.positive; + } else { + ++result.negative; + } + } - return result; -}; + return result; +} diff --git a/src/Numbers/staircase.js b/src/Numbers/staircase.js index 6a05c07..f09ff35 100644 --- a/src/Numbers/staircase.js +++ b/src/Numbers/staircase.js @@ -6,10 +6,10 @@ */ function staircase(n) { - let tmp = n; - for (let index = 0; index < n; index++) { - console.log(' '.repeat(--tmp) + '#'.repeat(index + 1)); - } + let tmp = n; + for (let index = 0; index < n; index++){ + console.log(' '.repeat(--tmp) + '#'.repeat(index + 1 )); + } } staircase(6); diff --git a/src/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js index 794c249..d6d9c81 100644 --- a/src/Sorting/bubble-sort.js +++ b/src/Sorting/bubble-sort.js @@ -6,22 +6,22 @@ */ function countSwaps(a) { - let isSorted = false; - let counter = 0; - while (!isSorted) { - isSorted = true; - for (let i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - [a[i], a[i + 1]] = [a[i + 1], a[i]]; - counter++; - isSorted = false; - } - } - } + let isSorted = false; + let counter = 0; + while (!isSorted) { + isSorted = true; + for (let i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + [a[i], a[i + 1]] = [a[i + 1], a[i]]; + counter++; + isSorted = false; + } + } + } - console.log(`Array is sorted in ${counter} swaps.`); - console.log(`First Element: ${a[0]}`); - console.log(`Last Element: ${a[a.length - 1]}`); + console.log(`Array is sorted in ${counter} swaps.`); + console.log(`First Element: ${a[0]}`); + console.log(`Last Element: ${a[a.length -1 ]}`); } countSwaps([5, 2, 1]); diff --git a/src/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js index 80dcd98..cabb6db 100644 --- a/src/Sorting/mark-and-toys.js +++ b/src/Sorting/mark-and-toys.js @@ -6,23 +6,20 @@ */ function maximumToys(prices, balance) { - prices = prices.sort((a, b) => a - b); - let toysBought = 0; - console.log(prices); - for (let i = 0; i < prices.length; i++) { - if (balance >= prices[i]) { - toysBought++; - balance -= prices[i]; - } else { - break; - } - } - return toysBought; + prices = prices.sort((a, b) => a - b) + let toysBought = 0; + console.log(prices); + for (let i = 0; i < prices.length; i++){ + if (balance >= prices[i]) { + toysBought++; + balance -= prices[i]; + } else { + break; + } + } + return toysBought; + } -const arr = [ - 33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, - 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, - 65846182, 8470661, 13597655, 360, -]; +let arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; console.log(maximumToys(arr, 100000)); diff --git a/src/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js index 79d6224..83bde36 100644 --- a/src/Sorting/mini-max-sum.js +++ b/src/Sorting/mini-max-sum.js @@ -6,14 +6,14 @@ */ function miniMaxSum(arr) { - const sum = [0, 0]; - arr = arr.sort((a, b) => a - b); - for (let i = 0; i < 4; i++) { - sum[0] += arr[i]; - sum[1] += arr[arr.length - (i + 1)]; - } + let sum = [0, 0]; + arr = arr.sort((a, b) => { return a - b }); + for (let i = 0; i < 4; i++){ + sum[0] += arr[i]; + sum[1] += arr[arr.length - (i+1)]; + } - console.log(sum[0], sum[1]); + console.log(sum[0], sum[1]); } miniMaxSum(1, 2, 3, 4, 5); diff --git a/src/Strings/alternating-characters.js b/src/Strings/alternating-characters.js index 3fbcb1a..b02de77 100644 --- a/src/Strings/alternating-characters.js +++ b/src/Strings/alternating-characters.js @@ -6,22 +6,22 @@ */ function alternatingCharacters(string) { - let prev = ''; - let counter = 0; - for (let index = 0; index < string.length; index++) { - if (!prev) { - prev = string[index]; - continue; - } + let prev = ''; + let counter = 0; + for (let index = 0; index < string.length; index++) { + if(!prev){ + prev = string[index]; + continue; + } - if (prev === string[index]) { - counter++; - } + if(prev === string[index]){ + counter++; + } - prev = string[index]; - } + prev = string[index]; + } - return counter; + return counter; } console.log(alternatingCharacters('BBBBB')); diff --git a/src/Strings/counting-valleys.js b/src/Strings/counting-valleys.js index b8c21eb..dbb44ae 100644 --- a/src/Strings/counting-valleys.js +++ b/src/Strings/counting-valleys.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/counting-valleys */ -module.exports = function countingValleys(n, s) { - let currentValley = 0; - let count = 0; - for (let i = 0; i < n; i++) { - if (s[i] === 'U') { - currentValley++; - } - if (s[i] === 'D') { - currentValley--; - } +function countingValleys(n, s) { + let currentValley = 0; + let count = 0; + for (let i = 0; i < n; i++) { - if (currentValley === 0 && s[i] === 'U') { - count++; - } - } + if (s[i] === 'U') { + currentValley++; + } + if (s[i] === 'D') { + currentValley--; + } - return count; -}; + if (currentValley == 0 && s[i] === 'U') { + count++; + } + } + + return count; + +} diff --git a/src/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js index 2564590..1e8ebbd 100644 --- a/src/Strings/hackerrank-in-string.js +++ b/src/Strings/hackerrank-in-string.js @@ -6,12 +6,12 @@ */ module.exports = function hackerrankInString(s) { - const mask = Array.from('hackerrank'); - for (let i = 0; i < s.length; i++) { - const currentChar = s.charAt(i); - if (mask[0] === currentChar) { - mask.shift(); - } - } - return mask.length === 0 ? 'YES' : 'NO'; + const mask = Array.from("hackerrank"); + for (let i = 0; i < s.length; i++) { + const currentChar = s.charAt(i); + if (mask[0] === currentChar) { + mask.shift(); + } + } + return mask.length === 0 ? "YES" : "NO"; }; diff --git a/src/Strings/making-anagrams.js b/src/Strings/making-anagrams.js index 3fb1d88..4de1579 100644 --- a/src/Strings/making-anagrams.js +++ b/src/Strings/making-anagrams.js @@ -4,44 +4,47 @@ Score: 25/ Link: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_r=internal-search */ + + +function makeAnagram(string1, string2){ + string1 = count(string1); + string2 = count(string2); + return findDiff(string1, string2); +} + function count(a) { - const arr = a.split('').sort(); - const counter = {}; - arr.forEach((value) => { - if (counter[value] !== undefined) { - counter[value] += 1; - } else { - counter[value] = 1; - } - }); - - return counter; + let arr = a.split('').sort(); + let counter = {}; + arr.forEach(value => { + if (counter[value] !== undefined) { + counter[value] += 1; + } else { + counter[value] = 1; + } + }) + + return counter; } function findDiff(arr1, arr2) { - let removeCount = 0; - - for (const key in arr1) { - if (!arr2[key]) { - removeCount += arr1[key]; - } else { - removeCount += Math.abs(arr2[key] - arr1[key]); - } - } - - for (const key in arr2) { - if (!arr1[key]) { - removeCount += arr2[key]; - } - } - return removeCount; -} + let removeCount = 0; -function makeAnagram(string1, string2) { - string1 = count(string1); - string2 = count(string2); - return findDiff(string1, string2); + for (let key in arr1) { + if (!arr2[key]) { + removeCount += arr1[key]; + } else { + removeCount += Math.abs(arr2[key] - arr1[key]); + } + } + + for (let key in arr2) { + if (!arr1[key]) { + removeCount += arr2[key]; + } + } + return removeCount; } -const a = 'fcrxzwscanmligyxyvym'; -const b = 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'; -console.log(makeAnagram(a, b)); + +let a = "fcrxzwscanmligyxyvym"; +let b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; +console.log(makeAnagram(a,b )); diff --git a/src/Strings/repeated-string.js b/src/Strings/repeated-string.js index 6e71159..4497df6 100644 --- a/src/Strings/repeated-string.js +++ b/src/Strings/repeated-string.js @@ -6,11 +6,11 @@ */ module.exports = function repeatedString(s, n) { - const initialCount = s.split('a').length - 1; - const cocent = Math.floor(n / s.length); - let total = cocent * initialCount; - const remainder = n % s.length; - const remaindLetter = s.slice(0, remainder); - total += remaindLetter.split('a').length - 1; - return total; -}; + let initialCount = s.split('a').length - 1; + let cocent = Math.floor(n / s.length); + let total = cocent * initialCount; + let remainder = n % s.length; + let remaindLetter = s.slice(0, remainder); + total += remaindLetter.split('a').length - 1; + return total; +} diff --git a/src/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js index 6b4a1cc..5846fcf 100644 --- a/src/Strings/sherlock-and-the-valid-string.js +++ b/src/Strings/sherlock-and-the-valid-string.js @@ -6,35 +6,36 @@ */ function isValid(string) { - const counter = {}; - - const arr = string.split('').sort(); - let smallValue = 0; - let allowedTimes = 0; - arr.forEach((element) => { - counter[element] = counter[element] === undefined ? 1 : counter[element] + 1; - }); - - for (const key in counter) { - if (smallValue === 0) { - smallValue = counter[key]; - continue; - } - - if (smallValue !== counter[key]) { - if (counter[key] === 1) { - allowedTimes += 1; - } else { - allowedTimes += Math.abs(smallValue - counter[key]); - } - } - - if (allowedTimes > 1) { - break; - } - } - - return !(allowedTimes > 1); + let counter = {}; + + let arr = string.split('').sort(); + let smallValue = 0; + let allowedTimes = 0; + arr.forEach(element => { + counter[element] = counter[element] === undefined ? 1 : counter[element]+1; + }); + + for(let key in counter){ + if(smallValue === 0){ + smallValue = counter[key]; + continue ; + } + + if(smallValue !== counter[key]){ + if(counter[key] === 1){ + allowedTimes += 1; + } else { + allowedTimes += Math.abs(smallValue - counter[key]); + } + } + + if(allowedTimes > 1){ + break; + } + } + + return allowedTimes > 1 ? false : true; } -console.log(isValid('abcdefghhgfedecba')); + +console.log(isValid("abcdefghhgfedecba")); diff --git a/src/Strings/strong-password.js b/src/Strings/strong-password.js index fa54fb6..d3fd7c0 100644 --- a/src/Strings/strong-password.js +++ b/src/Strings/strong-password.js @@ -6,21 +6,27 @@ */ module.exports = function passwordStrengthMinimumNumber(n, password) { - const STRONG_LENGTH = 6; - const missingChars = STRONG_LENGTH - n; - let score = 0; + const STRONG_LENGTH = 6; + const missingChars = STRONG_LENGTH - n; + let score = 0; - const passwordAsArray = Array.from(password); + const passwordAsArray = Array.from(password); - const hasNumber = passwordAsArray.some((char) => '0123456789'.includes(char)); - const hasLowerCase = passwordAsArray.some((char) => 'abcdefghijklmnopqrstuvwxyz'.includes(char)); - const hasUpperCase = passwordAsArray.some((char) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(char)); - const hasSpecialChar = passwordAsArray.some((char) => '!@#$%^&*()-+'.includes(char)); + const hasNumber = passwordAsArray.some(char => "0123456789".includes(char)); + const hasLowerCase = passwordAsArray.some(char => + "abcdefghijklmnopqrstuvwxyz".includes(char) + ); + const hasUpperCase = passwordAsArray.some(char => + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(char) + ); + const hasSpecialChar = passwordAsArray.some(char => + "!@#$%^&*()-+".includes(char) + ); - if (!hasNumber) score++; - if (!hasLowerCase) score++; - if (!hasUpperCase) score++; - if (!hasSpecialChar) score++; + if (!hasNumber) score++; + if (!hasLowerCase) score++; + if (!hasUpperCase) score++; + if (!hasSpecialChar) score++; - return Math.max(score, missingChars); + return Math.max(score, missingChars); }; diff --git a/src/Strings/time-conversion.js b/src/Strings/time-conversion.js index dc86243..6cabfbc 100644 --- a/src/Strings/time-conversion.js +++ b/src/Strings/time-conversion.js @@ -5,23 +5,24 @@ Link: https://www.hackerrank.com/challenges/time-conversion/ */ + module.exports = function timeConversion(time) { - const cycle = time.substring(time.length - 2, time.length); - const timeWithoutCycle = time.substring(0, time.length - 2); - const timeArr = timeWithoutCycle.split(':'); + let cycle = time.substring(time.length - 2, time.length); + let timeWithoutCycle = time.substring(0, time.length - 2); + let timeArr = timeWithoutCycle.split(':'); - if (cycle === 'AM') { - if (timeArr[0] !== '12') { - return timeWithoutCycle; - } + if (cycle === 'AM') { + if (timeArr[0] != 12) { + return timeWithoutCycle; + } - timeArr[0] = '00'; - return timeArr.join(':'); - } + timeArr[0] = '00'; + return timeArr.join(':'); + } - if (timeArr[0] !== '12') { - timeArr[0] = parseInt(timeArr[0], 10) + 12; - } + if (timeArr[0] != 12) { + timeArr[0] = parseInt(timeArr[0]) + 12; + } - return timeArr.join(':'); -}; + return timeArr.join(':') +} From ea7d291e3f7b77dcf4f1c83b16f1a26c2ec0fb27 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Thu, 28 Oct 2021 01:00:48 +0530 Subject: [PATCH 4/8] Fix eslint and add eslint to travis --- .editorconfig | 4 ++-- .eslintrc.json | 55 ++++++++++++++++++++++++++------------------------ .travis.yml | 2 +- package.json | 12 +++++++---- 4 files changed, 40 insertions(+), 33 deletions(-) diff --git a/.editorconfig b/.editorconfig index 1a6d62e..3281cce 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,9 +6,9 @@ end_of_line = lf indent_size = 2 indent_style = tab insert_final_newline = true -max_line_length = 130 +max_line_length = 155 trim_trailing_whitespace = true [*.md] -max_line_length = 130 +max_line_length = 155 trim_trailing_whitespace = true diff --git a/.eslintrc.json b/.eslintrc.json index fd4d4cf..a9d94b6 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,27 +1,30 @@ { - "env": { - "browser": true, - "commonjs": true, - "es2021": true - }, - "extends": [ - "eslint:recommended", - "airbnb-base" - ], - "parserOptions": { - "ecmaVersion": 12 - }, - "rules": { - "indent": ["error", "tab"], - "no-tabs": ["error", { "allowIndentationTabs": true }], - "max-len": ["error", { "code": 130 }], - "no-var": "error", - "semi": "error", - "no-multi-spaces": "error", - "space-in-parens": "error", - "no-multiple-empty-lines": "error", - "prefer-const": "error", - "no-use-before-define": "error" - } - } - + "env": { + "browser": true, + "commonjs": true, + "es2021": true + }, + "extends": ["eslint:recommended", "airbnb-base"], + "parserOptions": { + "ecmaVersion": 12 + }, + "rules": { + "indent": ["error", "tab"], + "no-tabs": ["warn", { "allowIndentationTabs": true }], + "max-len": ["error", { "code": 155 }], + "no-var": "error", + "semi": "error", + "no-multi-spaces": "error", + "space-in-parens": "error", + "no-multiple-empty-lines": "error", + "prefer-const": "error", + "no-use-before-define": "error", + "max-classes-per-file": ["warn", 1], + "no-plusplus": "off", + "no-param-reassign": "warn", + "no-restricted-syntax": "warn", + "no-continue": "warn", + "no-bitwise": "off", + "guard-for-in": "warn" + } +} diff --git a/.travis.yml b/.travis.yml index 9ef231a..133897e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,4 +6,4 @@ install: - npm install script: - npm run test -- npm run lint +- eslint src test --ext .js diff --git a/package.json b/package.json index f9db512..c819338 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,15 @@ "version": "1.0.0", "description": "Solutions for HackerRank Problems in Javascript.", "main": "index.js", + "nyc": { + "all": true, + "include": [ + "src/**/*.js" + ] + }, "scripts": { - "test": "mocha --recursive", - "report": "nyc mocha --recursive", - "prepare": "husky install", - "lint": "prettier --write **/*.*js && eslint --fix " + "test": "nyc mocha --recursive", + "prepare": "husky install" }, "lint-staged": { "*.js": [ From 0f65f54eb350a446fc723e7a6b3ee1c169caf008 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Thu, 28 Oct 2021 01:13:27 +0530 Subject: [PATCH 5/8] Fix eslint and add eslint to travis --- src/Arrays/2d-array-ds.js | 22 ++--- src/Arrays/apple-and-orange.js | 28 +++--- src/Arrays/array-manipulation.js | 18 ++-- src/Arrays/birthday-cake-candles.js | 24 ++--- src/Arrays/breaking-best-and-worst-records.js | 62 +++++++------ src/Arrays/compare-the-triplets.js | 20 ++--- src/Arrays/diagonal-difference.js | 21 +++-- src/Arrays/jumping-on-the-clouds.js | 31 ++++--- src/Arrays/left-rotation.js | 17 ++-- src/Arrays/minimum-swaps-2.js | 35 ++++---- src/Arrays/newyear-chaos.js | 36 ++++---- src/Arrays/sock-merchant.js | 36 ++++---- src/Data Structures/cycle-detection.js | 39 ++++---- .../reverse-doubly-linked-list.js | 85 +++++++++--------- .../count-triplet.js | 37 ++++---- .../custom-hashmap.js | 40 ++++----- .../frequency-queries.js | 58 ++++++------ .../game-of-thrones.js | 14 +-- src/Dictionaries and Hashmaps/ransom-note.js | 71 +++++++-------- .../sherlock-and-anagrams.js | 32 +++---- src/Dictionaries and Hashmaps/two-strings.js | 25 +++--- src/Numbers/grading.js | 27 +++--- src/Numbers/kangaroo.js | 44 +++++---- src/Numbers/plus-minus.js | 34 +++---- src/Numbers/staircase.js | 8 +- src/Sorting/bubble-sort.js | 30 +++---- src/Sorting/mark-and-toys.js | 29 +++--- src/Sorting/mini-max-sum.js | 14 +-- src/Strings/alternating-characters.js | 26 +++--- src/Strings/counting-valleys.js | 34 ++++--- src/Strings/hackerrank-in-string.js | 16 ++-- src/Strings/making-anagrams.js | 75 ++++++++-------- src/Strings/repeated-string.js | 16 ++-- src/Strings/sherlock-and-the-valid-string.js | 61 +++++++------ src/Strings/strong-password.js | 32 +++---- src/Strings/time-conversion.js | 31 ++++--- test/Arrays/birthday-cake-candles.test.js | 46 +++++----- test/Arrays/left-rotation.test.js | 34 ++++--- test/Data Structures/cycle-detection.test.js | 90 +++++++++---------- .../reverse-doubly-linked-list.test.js | 45 +++++----- test/Numbers/plus-minus.test.js | 26 +++--- test/Strings/hackerrank-in-string.test.js | 44 +++++---- test/Strings/repeated-string.test.js | 40 ++++----- test/Strings/strong-password.test.js | 29 +++--- test/Strings/time-conversion.test.js | 34 +++---- 45 files changed, 783 insertions(+), 833 deletions(-) diff --git a/src/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js index 1e5a28e..6bb6e73 100644 --- a/src/Arrays/2d-array-ds.js +++ b/src/Arrays/2d-array-ds.js @@ -4,14 +4,14 @@ Score: 15 Link: https://www.hackerrank.com/challenges/2d-array/ */ -function hourglassSum(arr) { - var sum = -1000 - let max = sum - for(let i = 0 ; i<4;i++){ - for(let j = 0 ; j<4; j++){ - sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] - if(sum>max) max = sum - } - } - console.log(max) -} +module.exports = function hourglassSum(arr) { + let sum = -1000; + let max = sum; + for (let i = 0; i < 4; i++) { + for (let j = 0; j < 4; j++) { + sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; + if (sum > max) max = sum; + } + } + console.log(max); +}; diff --git a/src/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js index ffaf16a..ca0011d 100644 --- a/src/Arrays/apple-and-orange.js +++ b/src/Arrays/apple-and-orange.js @@ -5,22 +5,20 @@ Link: https://www.hackerrank.com/challenges/apple-and-orange */ -function countApplesAndOranges(s, t, a, b, apples, oranges) { - countFruitsFallInsideHome(apples, s - a, t - a); - countFruitsFallInsideHome(oranges, s - b, t - b); -} - - function countFruitsFallInsideHome(fruits, startHome, EndHome) { - let counter = 0; - fruits.forEach(fruit => { - if (fruit >= startHome && fruit <= EndHome) { - return counter++; - } - }); + let counter = 0; + fruits.forEach((fruit) => { + if (fruit >= startHome && fruit <= EndHome) { + counter++; + } + return counter; + }); - return console.log(counter); + return console.log(counter); +} +function countApplesAndOranges(s, t, a, b, apples, oranges) { + countFruitsFallInsideHome(apples, s - a, t - a); + countFruitsFallInsideHome(oranges, s - b, t - b); } -countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1] , [5 -6]); - +countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1], [5 - 6]); diff --git a/src/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js index 45eaf1d..a04ae2b 100644 --- a/src/Arrays/array-manipulation.js +++ b/src/Arrays/array-manipulation.js @@ -5,14 +5,14 @@ Link: https://www.hackerrank.com/challenges/crush/problem */ -function arrayManipulation(n, queries) { - let arr = Array(n).fill(0); +module.exports = function arrayManipulation(n, queries) { + const arr = Array(n).fill(0); - for (let a = 0; a < queries.length; a++) { - for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { - arr[index] += queries[a][2]; - } - } + for (let a = 0; a < queries.length; a++) { + for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { + arr[index] += queries[a][2]; + } + } - return Math.max(...arr); -} + return Math.max(...arr); +}; diff --git a/src/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js index 35ed0d7..674311e 100644 --- a/src/Arrays/birthday-cake-candles.js +++ b/src/Arrays/birthday-cake-candles.js @@ -6,16 +6,16 @@ */ module.exports = function birthdayCakeCandles(arr) { - let tallestCandle = 0; - let candlesCounter = 0; - for (let index = 0; index < arr.length; index++) { - if (arr[index] > tallestCandle) { - tallestCandle = arr[index]; - candlesCounter = 1; - } else if (arr[index] === tallestCandle) { - candlesCounter++; - } - } + let tallestCandle = 0; + let candlesCounter = 0; + for (let index = 0; index < arr.length; index++) { + if (arr[index] > tallestCandle) { + tallestCandle = arr[index]; + candlesCounter = 1; + } else if (arr[index] === tallestCandle) { + candlesCounter++; + } + } - return candlesCounter; -} + return candlesCounter; +}; diff --git a/src/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js index 1afad77..9df7f33 100644 --- a/src/Arrays/breaking-best-and-worst-records.js +++ b/src/Arrays/breaking-best-and-worst-records.js @@ -6,37 +6,35 @@ */ function breakingRecords(scores) { - - let counters = { - min: 0, - max: 0 - }; - - let values = { - min: 0, - max: 0 - } - let isDefaultSet = false; - - scores.forEach(score => { - if (!isDefaultSet) { - values.min = score; - values.max = score; - isDefaultSet = true; - return ; - } - - if (score > values.max) { - values.max = score; - counters.max++; - } else if (score < values.min) { - values.min = score; - counters.min++; - } - }) - - return [counters.max, counters.min]; - + const counters = { + min: 0, + max: 0, + }; + + const values = { + min: 0, + max: 0, + }; + let isDefaultSet = false; + + scores.forEach((score) => { + if (!isDefaultSet) { + values.min = score; + values.max = score; + isDefaultSet = true; + return; + } + + if (score > values.max) { + values.max = score; + counters.max++; + } else if (score < values.min) { + values.min = score; + counters.min++; + } + }); + + return [counters.max, counters.min]; } -breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]) +breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]); diff --git a/src/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js index 75d6007..b542423 100644 --- a/src/Arrays/compare-the-triplets.js +++ b/src/Arrays/compare-the-triplets.js @@ -6,16 +6,16 @@ Link: https://www.hackerrank.com/challenges/compare-the-triplets/problem */ function compareTriplets(a, b) { - let points = [0, 0]; - for (let index = 0; index < a.length; index++){ - if (a[index] > b[index]) { - points[0] += 1; - } else if (a[index] < b[index]) { - points[1] += 1; - } - } + const points = [0, 0]; + for (let index = 0; index < a.length; index++) { + if (a[index] > b[index]) { + points[0] += 1; + } else if (a[index] < b[index]) { + points[1] += 1; + } + } - return points; + return points; } -console.log(compareTriplets([5, 6, 7], [3, 6, 10])) +console.log(compareTriplets([5, 6, 7], [3, 6, 10])); diff --git a/src/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js index 336b05d..5304e9e 100644 --- a/src/Arrays/diagonal-difference.js +++ b/src/Arrays/diagonal-difference.js @@ -1,4 +1,3 @@ - /* Title:Diagonal Difference Difficulty: Easy @@ -7,16 +6,16 @@ */ function diagonalDifference(arr) { - let leftToRight = 0; - let rightToLeft = 0; - let tmpLength = arr.length; - for (let i = 0; i < arr.length; i++){ - leftToRight += arr[i][i]; - rightToLeft += arr[i][--tmpLength]; - } + let leftToRight = 0; + let rightToLeft = 0; + let tmpLength = arr.length; + for (let i = 0; i < arr.length; i++) { + leftToRight += arr[i][i]; + rightToLeft += arr[i][--tmpLength]; + } - return Math.abs(leftToRight - rightToLeft); + return Math.abs(leftToRight - rightToLeft); } -let input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] -console.log(diagonalDifference(input)) +const input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]; +console.log(diagonalDifference(input)); diff --git a/src/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js index 9f5c7d1..0488a2f 100644 --- a/src/Arrays/jumping-on-the-clouds.js +++ b/src/Arrays/jumping-on-the-clouds.js @@ -5,20 +5,19 @@ Link: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ */ -function jumpingOnClouds(c) { +module.exports = function jumpingOnClouds(c) { + let jump = 0; + for (let i = 0; i < c.length;) { + if (c[i + 2] === 0) { + jump++; + i += 2; + } else if (c[i + 1] === 0) { + jump++; + i += 1; + } else { + i++; + } + } - let jump = 0; - for (let i = 0; i < c.length;){ - if (c[i + 2] == 0) { - jump++; - i += 2; - } else if (c[i + 1] == 0) { - jump++; - i += 1; - } else { - i++; - } - } - - return jump; -} + return jump; +}; diff --git a/src/Arrays/left-rotation.js b/src/Arrays/left-rotation.js index 17ed7de..7881ba7 100644 --- a/src/Arrays/left-rotation.js +++ b/src/Arrays/left-rotation.js @@ -6,14 +6,13 @@ */ module.exports = function rotLeft(a, d) { + if (!a.length) { + return []; + } - if(!a.length){ - return [] - } + for (let i = 0; i < d; i++) { + a.push(a.shift()); + } - for (let i = 0; i < d; i++) { - a.push(a.shift()); - } - - return a; -} + return a; +}; diff --git a/src/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js index c382556..95c93fc 100644 --- a/src/Arrays/minimum-swaps-2.js +++ b/src/Arrays/minimum-swaps-2.js @@ -5,22 +5,21 @@ Link: https://www.hackerrank.com/challenges/minimum-swaps-2 */ +module.exports = function minimumSwaps(arr) { + const origArray = arr.slice(0); + const sortedArray = arr.sort((a, b) => a - b); + let numberOfSwap = 0; + for (let i = 0; i < origArray.length; i++) { + if (origArray[i] !== sortedArray[i]) { + for (let j = i + 1; j < origArray.length; j++) { + if (origArray[j] === sortedArray[i]) { + [origArray[i], origArray[j]] = [origArray[j], origArray[i]]; + numberOfSwap++; + break; + } + } + } + } -function minimumSwaps(arr) { - var origArray = arr.slice(0); - var sortedArray = arr.sort((a,b) => a-b); - let numberOfSwap = 0; - for (var i = 0; i < origArray.length; i++) { - if (origArray[i] != sortedArray[i]) { - for (var j = i + 1; j < origArray.length; j++) { - if (origArray[j] === sortedArray[i]) { - [origArray[i], origArray[j]] = [origArray[j], origArray[i]] - numberOfSwap++ - break; - } - } - } - } - - return numberOfSwap; -} + return numberOfSwap; +}; diff --git a/src/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js index 0ae6270..08eb21a 100644 --- a/src/Arrays/newyear-chaos.js +++ b/src/Arrays/newyear-chaos.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/new-year-chaos/ */ -function minimumBribes(q) { - let swaps = 0; - let min = q.length; - for (var i = q.length -1 ; i >= 0; i--) { - if (q[i] - i > 3) { - return `Too chaotic`; - } - if (q[i] > i + 1) { - swaps += (q[i] - (i + 1)); - } else { - if (min > q[i]) { - min = q[i]; - } else if (q[i] != min) { - swaps++; - } - } - } +module.exports = function minimumBribes(q) { + let swaps = 0; + let min = q.length; + for (let i = q.length - 1; i >= 0; i--) { + if (q[i] - i > 3) { + return 'Too chaotic'; + } + if (q[i] > i + 1) { + swaps += (q[i] - (i + 1)); + } else if (min > q[i]) { + min = q[i]; + } else if (q[i] !== min) { + swaps++; + } + } - return swaps; -} + return swaps; +}; diff --git a/src/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js index e865834..c75cf50 100644 --- a/src/Arrays/sock-merchant.js +++ b/src/Arrays/sock-merchant.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/sock-merchant */ +module.exports = function sockMerchant(n, ar) { + const tmpArr = []; + let counter = 0; + ar.map((value) => { + if (tmpArr.includes(value)) { + const index = tmpArr.indexOf(value); + if (index > -1) { + tmpArr.splice(index, 1); + } + counter++; + } else { + tmpArr.push(value); + } + return value; + }); -function sockMerchant(n, ar) { - let tmpArr = []; - let counter = 0; - ar.map(value => { - if (tmpArr.includes(value)) { - var index = tmpArr.indexOf(value); - if (index > -1) { - tmpArr.splice(index, 1); - } - counter++; - } else { - tmpArr.push(value); - } - - }) - - return counter; - -} + return counter; +}; diff --git a/src/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js index 5bd280a..46ee960 100644 --- a/src/Data Structures/cycle-detection.js +++ b/src/Data Structures/cycle-detection.js @@ -6,30 +6,31 @@ */ function hasCycle(head) { - if (head === null || head.next === null || head.next.next === null) return false; // edge cases - let hare = head; - let tortoise = head; - do { - hare = hare.next.next; // 'hare' moves twice per tick - tortoise = tortoise.next; // 'tortoise' moves once per tick - } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); - return hare === tortoise; + if (head === null || head.next === null || head.next.next === null) return false; // edge cases + let hare = head; + let tortoise = head; + do { + hare = hare.next.next; // 'hare' moves twice per tick + tortoise = tortoise.next; // 'tortoise' moves once per tick + } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); + return hare === tortoise; } // NODE CLASS class Node { - constructor (data) { - this.data = data; - this.next = null; - } - insert (data) { - this.next = new Node(data); - return this.next; // for chaining - } + constructor(data) { + this.data = data; + this.next = null; + } + + insert(data) { + this.next = new Node(data); + return this.next; // for chaining + } } module.exports = { - hasCycle, - Node, -}; \ No newline at end of file + hasCycle, + Node, +}; diff --git a/src/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js index 04dcde3..3d4ae7d 100644 --- a/src/Data Structures/reverse-doubly-linked-list.js +++ b/src/Data Structures/reverse-doubly-linked-list.js @@ -1,56 +1,53 @@ -'use strict'; /* Title: Reverse a doubly linked list Difficulty: Easy Score: 5 Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem */ +class DoublyLinkedListNode { + constructor(nodeData) { + this.data = nodeData; + this.next = null; + this.prev = null; + } +} - -function reverse(head) { - while (head.next) { - head = head.next - } - - const newList = new DoublyLinkedList(); - - while (head) { - newList.insertNode(head.data); - head = head.prev - } - return newList.head +class DoublyLinkedList { + constructor() { + this.head = null; + this.tail = null; + } + + insertNode(nodeData) { + const node = new DoublyLinkedListNode(nodeData); + + if (this.head == null) { + this.head = node; + } else { + this.tail.next = node; + node.prev = this.tail; + } + + this.tail = node; + } } -class DoublyLinkedListNode { - constructor(nodeData) { - this.data = nodeData; - this.next = null; - this.prev = null; - } -}; +function reverse(head) { + while (head.next) { + head = head.next; + } -class DoublyLinkedList { - constructor() { - this.head = null; - this.tail = null; - } - - insertNode(nodeData) { - let node = new DoublyLinkedListNode(nodeData); - - if (this.head == null) { - this.head = node; - } else { - this.tail.next = node; - node.prev = this.tail; - } - - this.tail = node; - } -}; + const newList = new DoublyLinkedList(); -module.exports = { - reverse, - DoublyLinkedList, - DoublyLinkedListNode + while (head) { + newList.insertNode(head.data); + head = head.prev; + } + return newList.head; } + +module.exports = { + reverse, + DoublyLinkedList, + DoublyLinkedListNode, +}; diff --git a/src/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js index ac8d48c..38656ad 100644 --- a/src/Dictionaries and Hashmaps/count-triplet.js +++ b/src/Dictionaries and Hashmaps/count-triplet.js @@ -6,30 +6,29 @@ */ function countTriplets(arr, r) { - let second = {} - let third = {} - let count = 0; - for (let index = 0; index < arr.length; index++) { + const second = {}; + const third = {}; + let count = 0; + for (let index = 0; index < arr.length; index++) { + const val = arr[index]; - const val = arr[index]; + // If value found on third then add it to count + if (third[val]) { + count += third[val]; + } - //If value found on third then add it to count - if(third[val]){ - count += third[val]; - } + // If value found on second , convey it to third - //If value found on second , convey it to third + if (second[val]) { + third[val * r] = third[val * r] + second[val] || second[val]; + } - if(second[val]){ - third[val*r] = third[val*r] + second[val] || second[val]; - } + // add current element into second value - //add current element into second value + second[val * r] = second[val * r] + 1 || 1; + } - second[val*r] = second[val*r]+1 || 1; - } - - return count; + return count; } -console.log(countTriplets([1,2 ,2,4], 2)); +console.log(countTriplets([1, 2, 2, 4], 2)); diff --git a/src/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js index c2431ec..4c05db3 100644 --- a/src/Dictionaries and Hashmaps/custom-hashmap.js +++ b/src/Dictionaries and Hashmaps/custom-hashmap.js @@ -5,31 +5,31 @@ Link: - */ class customHashMap { - constructor() { - this.list = []; - } + constructor() { + this.list = []; + } - get(x) { - return this.list[this.hashCode(x)]; - } + get(x) { + return this.list[this.hashCode(x)]; + } - set(x, y) { - this.list[this.hashCode(x)] = y; - } + set(x, y) { + this.list[this.hashCode(x)] = y; + } - hashCode(str) { - let hash = 0; - if (str.length == 0) return hash; - for (let i = 0; i < str.length; i++) { - let char = str.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash = hash & hash; // Convert to 32bit integer - } - return hash; - } + static hashCode(str) { + let hash = 0; + if (str.length === 0) return hash; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash &= hash; // Convert to 32bit integer + } + return hash; + } } -let m = new customHashMap(); +const m = customHashMap(); m.set('hello', 'world'); console.log(m.get('hello')); diff --git a/src/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js index c3f4d5a..40ccb6b 100644 --- a/src/Dictionaries and Hashmaps/frequency-queries.js +++ b/src/Dictionaries and Hashmaps/frequency-queries.js @@ -6,40 +6,40 @@ */ function freqQuery(arr) { - const result = []; - const hash = {}; - const freq = []; + const result = []; + const hash = {}; + const freq = []; - for (let i = 0; i < arr.length; i += 1) { - const [action, value] = arr[i]; - const initValue = hash[value] || 0; + for (let i = 0; i < arr.length; i += 1) { + const [action, value] = arr[i]; + const initValue = hash[value] || 0; - if (action === 1) { - hash[value] = initValue + 1; - freq[initValue] = (freq[initValue] || 0) - 1; - freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; - } + if (action === 1) { + hash[value] = initValue + 1; + freq[initValue] = (freq[initValue] || 0) - 1; + freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; + } - if (action === 2 && initValue > 0) { - hash[value] = initValue - 1; - freq[initValue - 1] += 1; - freq[initValue] -= 1; - } + if (action === 2 && initValue > 0) { + hash[value] = initValue - 1; + freq[initValue - 1] += 1; + freq[initValue] -= 1; + } - if (action === 3) result.push(freq[value] > 0 ? 1 : 0); - } + if (action === 3) result.push(freq[value] > 0 ? 1 : 0); + } - return result; + return result; } -let input = [ - [1, 5], - [1, 6], - [3, 2], - [1, 10], - [1, 10], - [1, 6], - [2, 5], - [3, 2] - ]; +const input = [ + [1, 5], + [1, 6], + [3, 2], + [1, 10], + [1, 10], + [1, 6], + [2, 5], + [3, 2], +]; console.log(freqQuery(input)); diff --git a/src/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js index 0d50f1e..31e1f31 100644 --- a/src/Dictionaries and Hashmaps/game-of-thrones.js +++ b/src/Dictionaries and Hashmaps/game-of-thrones.js @@ -6,12 +6,12 @@ */ function gameOfThrones(s) { - const frequencies = {}; - for (let char of s) frequencies[char] = frequencies[char] + 1 || 1; - let oddFrequencies = Object.values(frequencies).filter(frequency => frequency % 2); - return oddFrequencies.length <= 1 ? 'YES' : 'NO'; + const frequencies = {}; + for (const char of s) frequencies[char] = frequencies[char] + 1 || 1; + const oddFrequencies = Object.values(frequencies).filter((frequency) => frequency % 2); + return oddFrequencies.length <= 1 ? 'YES' : 'NO'; } -console.log(gameOfThrones('aaabbbb')); // YES -console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO -console.log(gameOfThrones('cdcdcdcdeeeef')); // YES \ No newline at end of file +console.log(gameOfThrones('aaabbbb')); // YES +console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO +console.log(gameOfThrones('cdcdcdcdeeeef')); // YES diff --git a/src/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js index bf7003a..2268c69 100644 --- a/src/Dictionaries and Hashmaps/ransom-note.js +++ b/src/Dictionaries and Hashmaps/ransom-note.js @@ -6,51 +6,48 @@ */ class ExtendedMap { - - constructor(){ - this.map = new Map(); - } - - get(x) { - let value = this.map.get(x); - if (value === 1) { - this.map.delete(x); - return true; - } - - return this.map.set(x, --value); - } - - set(x, y) { - if (this.map.get(x)) { - return this.map.set(x, this.map.get(x) + 1); - } - - return this.map.set(x, y); - } + constructor() { + this.map = new Map(); + } + + get(x) { + let value = this.map.get(x); + if (value === 1) { + this.map.delete(x); + return true; + } + + return this.map.set(x, --value); + } + + set(x, y) { + if (this.map.get(x)) { + return this.map.set(x, this.map.get(x) + 1); + } + + return this.map.set(x, y); + } } - function checkMagazine(magazine, note) { + const m = new ExtendedMap(); - let m = new ExtendedMap() - - for (let i = 0; i < magazine.length; i++) { - m.set(magazine[i], 1) - } + for (let i = 0; i < magazine.length; i++) { + m.set(magazine[i], 1); + } - for (let i = 0; i < note.length; i++) { - if (!m.get(note[i])) { - console.log('No'); - return; - }; - } + for (let i = 0; i < note.length; i++) { + if (!m.get(note[i])) { + console.log('No'); + return; + } + } - console.log('Yes'); + console.log('Yes'); } -let magazine = [ 'give', 'me', 'one', 'grand', 'today', 'night' ]; -let note = [ 'give', 'one', 'grand', 'today' ]; +const magazine = ['give', 'me', 'one', 'grand', 'today', 'night']; +const note = ['give', 'one', 'grand', 'today']; console.time('Time Taken'); checkMagazine(magazine, note); diff --git a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js index 138f0db..8b655d9 100644 --- a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js +++ b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js @@ -5,23 +5,23 @@ Link: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ */ function sherlockAndAnagrams(s) { - let count = 0; - let strLength = s.length; //get length - for (let i = 1; i < strLength; i++) { - let found = {}; - for (let j = 0; j + i <= strLength; j++) { - let substr = s.substr(j, i); //device string into substr - substr = substr.split('').sort().join(''); //sort it - if (found[substr]) { - count += found[substr]; //count total - found[substr]++; - } else { - found[substr] = 1; - } - } - } + let count = 0; + const strLength = s.length; // get length + for (let i = 1; i < strLength; i++) { + const found = {}; + for (let j = 0; j + i <= strLength; j++) { + let substr = s.substr(j, i); // device string into substr + substr = substr.split('').sort().join(''); // sort it + if (found[substr]) { + count += found[substr]; // count total + found[substr]++; + } else { + found[substr] = 1; + } + } + } - return count; + return count; } console.log(sherlockAndAnagrams('cdcd')); diff --git a/src/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js index f9f7e3d..cc1845d 100644 --- a/src/Dictionaries and Hashmaps/two-strings.js +++ b/src/Dictionaries and Hashmaps/two-strings.js @@ -6,22 +6,21 @@ */ function twoStrings(s1, s2) { - m = new Map(); - for(let i=0; i { - if (grade < 38) { - return grade; - } +module.exports = function gradingStudents(grades) { + const newGrades = grades.map((grade) => { + if (grade < 38) { + return grade; + } - let roundRemainder = grade % 5; + const roundRemainder = grade % 5; - if (roundRemainder === 0 || roundRemainder <= 2) { - return grade; - } + if (roundRemainder === 0 || roundRemainder <= 2) { + return grade; + } - return grade + (5 - roundRemainder); - }) + return grade + (5 - roundRemainder); + }); - return newGrades; - -} + return newGrades; +}; diff --git a/src/Numbers/kangaroo.js b/src/Numbers/kangaroo.js index 06495a1..90ae9da 100644 --- a/src/Numbers/kangaroo.js +++ b/src/Numbers/kangaroo.js @@ -7,29 +7,26 @@ // Solution 1 function kangaroo(x1, v1, x2, v2) { - if ((x2 > x1 && v2 > v1) || v1 === v2) { - return 'NO'; - } + if ((x2 > x1 && v2 > v1) || v1 === v2) { + return 'NO'; + } - let x1Distance = x1; - let x2Distance = x2; + let x1Distance = x1; + let x2Distance = x2; - while (x1Distance !== x2Distance) { - x1Distance += v1; - x2Distance += v2; + while (x1Distance !== x2Distance) { + x1Distance += v1; + x2Distance += v2; - if (x1Distance > x2Distance) { - return 'NO'; - } - } - - return 'YES'; + if (x1Distance > x2Distance) { + return 'NO'; + } + } + return 'YES'; } - -//Solution 2 - +// Solution 2 /* @@ -46,11 +43,12 @@ x1 - x2 / v2 - v1 = y so we can find y with all 4 inputs if it is integer and greater than 0 then both will meet */ -function kangaroo(x1, v1, x2, v2) { - if (x2 > x1 && v2 > v1) { - return 'NO' - } +function kangarooSolution2(x1, v1, x2, v2) { + if (x2 > x1 && v2 > v1) { + return 'NO'; + } - let steps = (x1 - x2) % (v2 - v1); - return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; + const steps = (x1 - x2) % (v2 - v1); + return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; } +module.exports = [kangaroo, kangarooSolution2]; diff --git a/src/Numbers/plus-minus.js b/src/Numbers/plus-minus.js index b754238..164be6c 100644 --- a/src/Numbers/plus-minus.js +++ b/src/Numbers/plus-minus.js @@ -6,22 +6,22 @@ */ module.exports = function plusMinus(arr) { - let result = { - positive: 0, - negative: 0, - zero: 0, - } + const result = { + positive: 0, + negative: 0, + zero: 0, + }; - let arrLength = arr.length; - for (let index = 0; index < arrLength; index++){ - if (arr[index] === 0) { - ++result.zero; - } else if (arr[index] > 0) { - ++result.positive; - } else { - ++result.negative; - } - } + const arrLength = arr.length; + for (let index = 0; index < arrLength; index++) { + if (arr[index] === 0) { + ++result.zero; + } else if (arr[index] > 0) { + ++result.positive; + } else { + ++result.negative; + } + } - return result; -} + return result; +}; diff --git a/src/Numbers/staircase.js b/src/Numbers/staircase.js index f09ff35..6a05c07 100644 --- a/src/Numbers/staircase.js +++ b/src/Numbers/staircase.js @@ -6,10 +6,10 @@ */ function staircase(n) { - let tmp = n; - for (let index = 0; index < n; index++){ - console.log(' '.repeat(--tmp) + '#'.repeat(index + 1 )); - } + let tmp = n; + for (let index = 0; index < n; index++) { + console.log(' '.repeat(--tmp) + '#'.repeat(index + 1)); + } } staircase(6); diff --git a/src/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js index d6d9c81..794c249 100644 --- a/src/Sorting/bubble-sort.js +++ b/src/Sorting/bubble-sort.js @@ -6,22 +6,22 @@ */ function countSwaps(a) { - let isSorted = false; - let counter = 0; - while (!isSorted) { - isSorted = true; - for (let i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - [a[i], a[i + 1]] = [a[i + 1], a[i]]; - counter++; - isSorted = false; - } - } - } + let isSorted = false; + let counter = 0; + while (!isSorted) { + isSorted = true; + for (let i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + [a[i], a[i + 1]] = [a[i + 1], a[i]]; + counter++; + isSorted = false; + } + } + } - console.log(`Array is sorted in ${counter} swaps.`); - console.log(`First Element: ${a[0]}`); - console.log(`Last Element: ${a[a.length -1 ]}`); + console.log(`Array is sorted in ${counter} swaps.`); + console.log(`First Element: ${a[0]}`); + console.log(`Last Element: ${a[a.length - 1]}`); } countSwaps([5, 2, 1]); diff --git a/src/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js index cabb6db..6741a0d 100644 --- a/src/Sorting/mark-and-toys.js +++ b/src/Sorting/mark-and-toys.js @@ -6,20 +6,21 @@ */ function maximumToys(prices, balance) { - prices = prices.sort((a, b) => a - b) - let toysBought = 0; - console.log(prices); - for (let i = 0; i < prices.length; i++){ - if (balance >= prices[i]) { - toysBought++; - balance -= prices[i]; - } else { - break; - } - } - return toysBought; - + prices = prices.sort((a, b) => a - b); + let toysBought = 0; + console.log(prices); + for (let i = 0; i < prices.length; i++) { + if (balance >= prices[i]) { + toysBought++; + balance -= prices[i]; + } else { + break; + } + } + return toysBought; } -let arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; +const arr = [33324560, 77661073, 31948330, + 21522343, 97176507, 5724692, 24699815, + 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; console.log(maximumToys(arr, 100000)); diff --git a/src/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js index 83bde36..79d6224 100644 --- a/src/Sorting/mini-max-sum.js +++ b/src/Sorting/mini-max-sum.js @@ -6,14 +6,14 @@ */ function miniMaxSum(arr) { - let sum = [0, 0]; - arr = arr.sort((a, b) => { return a - b }); - for (let i = 0; i < 4; i++){ - sum[0] += arr[i]; - sum[1] += arr[arr.length - (i+1)]; - } + const sum = [0, 0]; + arr = arr.sort((a, b) => a - b); + for (let i = 0; i < 4; i++) { + sum[0] += arr[i]; + sum[1] += arr[arr.length - (i + 1)]; + } - console.log(sum[0], sum[1]); + console.log(sum[0], sum[1]); } miniMaxSum(1, 2, 3, 4, 5); diff --git a/src/Strings/alternating-characters.js b/src/Strings/alternating-characters.js index b02de77..3fbcb1a 100644 --- a/src/Strings/alternating-characters.js +++ b/src/Strings/alternating-characters.js @@ -6,22 +6,22 @@ */ function alternatingCharacters(string) { - let prev = ''; - let counter = 0; - for (let index = 0; index < string.length; index++) { - if(!prev){ - prev = string[index]; - continue; - } + let prev = ''; + let counter = 0; + for (let index = 0; index < string.length; index++) { + if (!prev) { + prev = string[index]; + continue; + } - if(prev === string[index]){ - counter++; - } + if (prev === string[index]) { + counter++; + } - prev = string[index]; - } + prev = string[index]; + } - return counter; + return counter; } console.log(alternatingCharacters('BBBBB')); diff --git a/src/Strings/counting-valleys.js b/src/Strings/counting-valleys.js index dbb44ae..b8c21eb 100644 --- a/src/Strings/counting-valleys.js +++ b/src/Strings/counting-valleys.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/counting-valleys */ -function countingValleys(n, s) { - let currentValley = 0; - let count = 0; - for (let i = 0; i < n; i++) { +module.exports = function countingValleys(n, s) { + let currentValley = 0; + let count = 0; + for (let i = 0; i < n; i++) { + if (s[i] === 'U') { + currentValley++; + } + if (s[i] === 'D') { + currentValley--; + } - if (s[i] === 'U') { - currentValley++; - } - if (s[i] === 'D') { - currentValley--; - } + if (currentValley === 0 && s[i] === 'U') { + count++; + } + } - if (currentValley == 0 && s[i] === 'U') { - count++; - } - } - - return count; - -} + return count; +}; diff --git a/src/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js index 1e8ebbd..2564590 100644 --- a/src/Strings/hackerrank-in-string.js +++ b/src/Strings/hackerrank-in-string.js @@ -6,12 +6,12 @@ */ module.exports = function hackerrankInString(s) { - const mask = Array.from("hackerrank"); - for (let i = 0; i < s.length; i++) { - const currentChar = s.charAt(i); - if (mask[0] === currentChar) { - mask.shift(); - } - } - return mask.length === 0 ? "YES" : "NO"; + const mask = Array.from('hackerrank'); + for (let i = 0; i < s.length; i++) { + const currentChar = s.charAt(i); + if (mask[0] === currentChar) { + mask.shift(); + } + } + return mask.length === 0 ? 'YES' : 'NO'; }; diff --git a/src/Strings/making-anagrams.js b/src/Strings/making-anagrams.js index 4de1579..ffc8d75 100644 --- a/src/Strings/making-anagrams.js +++ b/src/Strings/making-anagrams.js @@ -4,47 +4,42 @@ Score: 25/ Link: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_r=internal-search */ - - -function makeAnagram(string1, string2){ - string1 = count(string1); - string2 = count(string2); - return findDiff(string1, string2); -} - function count(a) { - let arr = a.split('').sort(); - let counter = {}; - arr.forEach(value => { - if (counter[value] !== undefined) { - counter[value] += 1; - } else { - counter[value] = 1; - } - }) - - return counter; + const arr = a.split('').sort(); + const counter = {}; + arr.forEach((value) => { + if (counter[value] !== undefined) { + counter[value] += 1; + } else { + counter[value] = 1; + } + }); + + return counter; } - function findDiff(arr1, arr2) { - let removeCount = 0; - - for (let key in arr1) { - if (!arr2[key]) { - removeCount += arr1[key]; - } else { - removeCount += Math.abs(arr2[key] - arr1[key]); - } - } - - for (let key in arr2) { - if (!arr1[key]) { - removeCount += arr2[key]; - } - } - return removeCount; + let removeCount = 0; + + for (const key in arr1) { + if (!arr2[key]) { + removeCount += arr1[key]; + } else { + removeCount += Math.abs(arr2[key] - arr1[key]); + } + } + + for (const key in arr2) { + if (!arr1[key]) { + removeCount += arr2[key]; + } + } + return removeCount; } - -let a = "fcrxzwscanmligyxyvym"; -let b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; -console.log(makeAnagram(a,b )); +function makeAnagram(string1, string2) { + string1 = count(string1); + string2 = count(string2); + return findDiff(string1, string2); +} +const a = 'fcrxzwscanmligyxyvym'; +const b = 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'; +console.log(makeAnagram(a, b)); diff --git a/src/Strings/repeated-string.js b/src/Strings/repeated-string.js index 4497df6..6e71159 100644 --- a/src/Strings/repeated-string.js +++ b/src/Strings/repeated-string.js @@ -6,11 +6,11 @@ */ module.exports = function repeatedString(s, n) { - let initialCount = s.split('a').length - 1; - let cocent = Math.floor(n / s.length); - let total = cocent * initialCount; - let remainder = n % s.length; - let remaindLetter = s.slice(0, remainder); - total += remaindLetter.split('a').length - 1; - return total; -} + const initialCount = s.split('a').length - 1; + const cocent = Math.floor(n / s.length); + let total = cocent * initialCount; + const remainder = n % s.length; + const remaindLetter = s.slice(0, remainder); + total += remaindLetter.split('a').length - 1; + return total; +}; diff --git a/src/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js index 5846fcf..d786906 100644 --- a/src/Strings/sherlock-and-the-valid-string.js +++ b/src/Strings/sherlock-and-the-valid-string.js @@ -6,36 +6,35 @@ */ function isValid(string) { - let counter = {}; - - let arr = string.split('').sort(); - let smallValue = 0; - let allowedTimes = 0; - arr.forEach(element => { - counter[element] = counter[element] === undefined ? 1 : counter[element]+1; - }); - - for(let key in counter){ - if(smallValue === 0){ - smallValue = counter[key]; - continue ; - } - - if(smallValue !== counter[key]){ - if(counter[key] === 1){ - allowedTimes += 1; - } else { - allowedTimes += Math.abs(smallValue - counter[key]); - } - } - - if(allowedTimes > 1){ - break; - } - } - - return allowedTimes > 1 ? false : true; + const counter = {}; + + const arr = string.split('').sort(); + let smallValue = 0; + let allowedTimes = 0; + arr.forEach((element) => { + counter[element] = counter[element] === undefined ? 1 : counter[element] + 1; + }); + + for (const key in counter) { + if (smallValue === 0) { + smallValue = counter[key]; + continue; + } + + if (smallValue !== counter[key]) { + if (counter[key] === 1) { + allowedTimes += 1; + } else { + allowedTimes += Math.abs(smallValue - counter[key]); + } + } + + if (allowedTimes > 1) { + break; + } + } + + return !(allowedTimes > 1); } - -console.log(isValid("abcdefghhgfedecba")); +console.log(isValid('abcdefghhgfedecba')); diff --git a/src/Strings/strong-password.js b/src/Strings/strong-password.js index d3fd7c0..fa54fb6 100644 --- a/src/Strings/strong-password.js +++ b/src/Strings/strong-password.js @@ -6,27 +6,21 @@ */ module.exports = function passwordStrengthMinimumNumber(n, password) { - const STRONG_LENGTH = 6; - const missingChars = STRONG_LENGTH - n; - let score = 0; + const STRONG_LENGTH = 6; + const missingChars = STRONG_LENGTH - n; + let score = 0; - const passwordAsArray = Array.from(password); + const passwordAsArray = Array.from(password); - const hasNumber = passwordAsArray.some(char => "0123456789".includes(char)); - const hasLowerCase = passwordAsArray.some(char => - "abcdefghijklmnopqrstuvwxyz".includes(char) - ); - const hasUpperCase = passwordAsArray.some(char => - "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(char) - ); - const hasSpecialChar = passwordAsArray.some(char => - "!@#$%^&*()-+".includes(char) - ); + const hasNumber = passwordAsArray.some((char) => '0123456789'.includes(char)); + const hasLowerCase = passwordAsArray.some((char) => 'abcdefghijklmnopqrstuvwxyz'.includes(char)); + const hasUpperCase = passwordAsArray.some((char) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(char)); + const hasSpecialChar = passwordAsArray.some((char) => '!@#$%^&*()-+'.includes(char)); - if (!hasNumber) score++; - if (!hasLowerCase) score++; - if (!hasUpperCase) score++; - if (!hasSpecialChar) score++; + if (!hasNumber) score++; + if (!hasLowerCase) score++; + if (!hasUpperCase) score++; + if (!hasSpecialChar) score++; - return Math.max(score, missingChars); + return Math.max(score, missingChars); }; diff --git a/src/Strings/time-conversion.js b/src/Strings/time-conversion.js index 6cabfbc..dc86243 100644 --- a/src/Strings/time-conversion.js +++ b/src/Strings/time-conversion.js @@ -5,24 +5,23 @@ Link: https://www.hackerrank.com/challenges/time-conversion/ */ - module.exports = function timeConversion(time) { - let cycle = time.substring(time.length - 2, time.length); - let timeWithoutCycle = time.substring(0, time.length - 2); - let timeArr = timeWithoutCycle.split(':'); + const cycle = time.substring(time.length - 2, time.length); + const timeWithoutCycle = time.substring(0, time.length - 2); + const timeArr = timeWithoutCycle.split(':'); - if (cycle === 'AM') { - if (timeArr[0] != 12) { - return timeWithoutCycle; - } + if (cycle === 'AM') { + if (timeArr[0] !== '12') { + return timeWithoutCycle; + } - timeArr[0] = '00'; - return timeArr.join(':'); - } + timeArr[0] = '00'; + return timeArr.join(':'); + } - if (timeArr[0] != 12) { - timeArr[0] = parseInt(timeArr[0]) + 12; - } + if (timeArr[0] !== '12') { + timeArr[0] = parseInt(timeArr[0], 10) + 12; + } - return timeArr.join(':') -} + return timeArr.join(':'); +}; diff --git a/test/Arrays/birthday-cake-candles.test.js b/test/Arrays/birthday-cake-candles.test.js index 5d43aba..506cc68 100644 --- a/test/Arrays/birthday-cake-candles.test.js +++ b/test/Arrays/birthday-cake-candles.test.js @@ -1,28 +1,28 @@ -const birthdayCakeCandles = require("../../src/Arrays/birthday-cake-candles"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const birthdayCakeCandles = require('../../src/Arrays/birthday-cake-candles'); -describe("Birthday Cake Candles", () => { - it("returns 0 for empty array", () => { - expect(birthdayCakeCandles([])).to.equal(0); - }); +describe('Birthday Cake Candles', () => { + it('returns 0 for empty array', () => { + expect(birthdayCakeCandles([])).to.equal(0); + }); - it("returns 1 if there is only one candle", () => { - expect(birthdayCakeCandles([1])).to.equal(1); - expect(birthdayCakeCandles([2])).to.equal(1); - expect(birthdayCakeCandles([3])).to.equal(1); - }); + it('returns 1 if there is only one candle', () => { + expect(birthdayCakeCandles([1])).to.equal(1); + expect(birthdayCakeCandles([2])).to.equal(1); + expect(birthdayCakeCandles([3])).to.equal(1); + }); - it("returns 2 if there are two candles with the same height", () => { - expect(birthdayCakeCandles([1, 1])).to.equal(2); - expect(birthdayCakeCandles([2, 2])).to.equal(2); - expect(birthdayCakeCandles([3, 3])).to.equal(2); - }); + it('returns 2 if there are two candles with the same height', () => { + expect(birthdayCakeCandles([1, 1])).to.equal(2); + expect(birthdayCakeCandles([2, 2])).to.equal(2); + expect(birthdayCakeCandles([3, 3])).to.equal(2); + }); - it("returns correct amount for array with different sized candles", () => { - expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); - expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); - expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); - expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); - }); + it('returns correct amount for array with different sized candles', () => { + expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); + expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); + expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); + expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); + }); }); diff --git a/test/Arrays/left-rotation.test.js b/test/Arrays/left-rotation.test.js index 2a4e66a..0965ab2 100644 --- a/test/Arrays/left-rotation.test.js +++ b/test/Arrays/left-rotation.test.js @@ -1,22 +1,20 @@ -const leftRotation = require('../../src/Arrays/left-rotation') -const { describe, it } = require('mocha') -const { expect } = require('chai') +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const leftRotation = require('../../src/Arrays/left-rotation'); describe('Left Rotation', () => { + it('should work for any empty array', () => { + expect(leftRotation([], 10)).to.deep.equal([]); + }); - it('should work for any empty array', () => { - expect(leftRotation([], 10)).to.deep.equal([]) - }) + it('should work for a 1 element array', () => { + const original = [1]; + expect(leftRotation(original, 10)).to.deep.equal(original); + }); - it('should work for a 1 element array', () => { - const original = [1] - expect(leftRotation(original, 10)).to.deep.equal(original) - }) - - it('should work for multiple elements', () => { - const original = "ABCDEF".split('') - const expected = "DEFABC".split('') - expect(leftRotation(original, 3)).to.deep.equal(expected) - }) - -}) + it('should work for multiple elements', () => { + const original = 'ABCDEF'.split(''); + const expected = 'DEFABC'.split(''); + expect(leftRotation(original, 3)).to.deep.equal(expected); + }); +}); diff --git a/test/Data Structures/cycle-detection.test.js b/test/Data Structures/cycle-detection.test.js index 32fdcb7..24bbb2e 100644 --- a/test/Data Structures/cycle-detection.test.js +++ b/test/Data Structures/cycle-detection.test.js @@ -1,54 +1,54 @@ -const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); const { describe, it } = require('mocha'); const { expect } = require('chai'); +const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); describe('Cycle Detection', () => { - it('should detect a cycle in a regular linked list', () => { - const test1 = new Node(1); - const tail1 = test1.insert(2) // tail1 === Node #8 - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - const connection1 = test1.next.next.next; // connection1 === Node #4 - tail1.next = connection1; - expect(hasCycle(test1)).to.equal(true); - }); + it('should detect a cycle in a regular linked list', () => { + const test1 = new Node(1); + const tail1 = test1.insert(2) // tail1 === Node #8 + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + const connection1 = test1.next.next.next; // connection1 === Node #4 + tail1.next = connection1; + expect(hasCycle(test1)).to.equal(true); + }); - it('should return false when the end of the list points to null', () => { - const test2 = new Node(1); - test2.insert(2) - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - expect(hasCycle(test2)).to.equal(false); - }); + it('should return false when the end of the list points to null', () => { + const test2 = new Node(1); + test2.insert(2) + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + expect(hasCycle(test2)).to.equal(false); + }); - it('should return false when head is null instead of a node', () => { - const test3 = null; - expect(hasCycle(test3)).to.equal(false); - }); + it('should return false when head is null instead of a node', () => { + const test3 = null; + expect(hasCycle(test3)).to.equal(false); + }); - it('should return false when the linked list only has one node that points to null', () => { - const test4 = new Node(1); - expect(hasCycle(test4)).to.equal(false); - }); + it('should return false when the linked list only has one node that points to null', () => { + const test4 = new Node(1); + expect(hasCycle(test4)).to.equal(false); + }); - it('should return false when the linked list only has two nodes', () => { - const test5 = new Node(1); - test5.insert(2); - expect(hasCycle(test5)).to.equal(false); - }); + it('should return false when the linked list only has two nodes', () => { + const test5 = new Node(1); + test5.insert(2); + expect(hasCycle(test5)).to.equal(false); + }); - it('should return false when the linked list only has two nodes but the tail links to head', () => { - const test6 = new Node(1); - const tail6 = test6.insert(2); // tail6 === Node #2 - tail6.next = test6; - expect(hasCycle(test6)).to.equal(true); - }); -}) + it('should return false when the linked list only has two nodes but the tail links to head', () => { + const test6 = new Node(1); + const tail6 = test6.insert(2); // tail6 === Node #2 + tail6.next = test6; + expect(hasCycle(test6)).to.equal(true); + }); +}); diff --git a/test/Data Structures/reverse-doubly-linked-list.test.js b/test/Data Structures/reverse-doubly-linked-list.test.js index 4acc443..7545ba3 100644 --- a/test/Data Structures/reverse-doubly-linked-list.test.js +++ b/test/Data Structures/reverse-doubly-linked-list.test.js @@ -1,29 +1,28 @@ +const { describe, it } = require('mocha'); +const { expect } = require('chai'); const { reverse, DoublyLinkedListNode, DoublyLinkedList } = require('../../src/Data Structures/reverse-doubly-linked-list'); -const { describe, it } = require('mocha') -const { expect } = require('chai') - describe('Reverse Doubly Linked List', () => { - it('should reverse an empty list', () => { - let node = new DoublyLinkedListNode(1) - expect(reverse(node)).to.deep.equal(node) - }) + it('should reverse an empty list', () => { + const node = new DoublyLinkedListNode(1); + expect(reverse(node)).to.deep.equal(node); + }); - it('should reverse a chain of linked nodes', () => { - let list = new DoublyLinkedList(); - list.insertNode(1) - list.insertNode(2) - list.insertNode(3) - list.insertNode(4) - list.insertNode(5) + it('should reverse a chain of linked nodes', () => { + const list = new DoublyLinkedList(); + list.insertNode(1); + list.insertNode(2); + list.insertNode(3); + list.insertNode(4); + list.insertNode(5); - let reversedList = new DoublyLinkedList(); - reversedList.insertNode(5) - reversedList.insertNode(4) - reversedList.insertNode(3) - reversedList.insertNode(2) - reversedList.insertNode(1) + const reversedList = new DoublyLinkedList(); + reversedList.insertNode(5); + reversedList.insertNode(4); + reversedList.insertNode(3); + reversedList.insertNode(2); + reversedList.insertNode(1); - expect(reverse(list.head)).to.deep.equal(reversedList.head) - }) -}) \ No newline at end of file + expect(reverse(list.head)).to.deep.equal(reversedList.head); + }); +}); diff --git a/test/Numbers/plus-minus.test.js b/test/Numbers/plus-minus.test.js index 7fa3ced..86cc971 100644 --- a/test/Numbers/plus-minus.test.js +++ b/test/Numbers/plus-minus.test.js @@ -1,17 +1,17 @@ -const plusMinus = require('../../src/Numbers/plus-minus') -const { describe, it } = require('mocha') -const { expect } = require('chai') +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const plusMinus = require('../../src/Numbers/plus-minus'); describe('Plus Minus Problem', () => { - it('It should Return 2 Positive 2 Negative and 1 Zero', () => { - expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({positive: 2, negative: 2, zero: 1 }); - }); + it('It should Return 2 Positive 2 Negative and 1 Zero', () => { + expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({ positive: 2, negative: 2, zero: 1 }); + }); - it('It should Return 5 Positive', () => { - expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({positive: 5, negative: 0, zero: 0 }); - }); + it('It should Return 5 Positive', () => { + expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({ positive: 5, negative: 0, zero: 0 }); + }); - it('It should Return 5 Negative', () => { - expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({positive: 0, negative: 5, zero: 0 }); - }); -}) + it('It should Return 5 Negative', () => { + expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({ positive: 0, negative: 5, zero: 0 }); + }); +}); diff --git a/test/Strings/hackerrank-in-string.test.js b/test/Strings/hackerrank-in-string.test.js index 349627c..fdbd886 100644 --- a/test/Strings/hackerrank-in-string.test.js +++ b/test/Strings/hackerrank-in-string.test.js @@ -1,28 +1,24 @@ -const hackerrankInString = require("../../src/Strings/hackerrank-in-string"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const hackerrankInString = require('../../src/Strings/hackerrank-in-string'); -describe("HackerRank in a String", () => { - it("should return NO for any empty string", () => { - expect(hackerrankInString("")).to.equal("NO"); - }); +describe('HackerRank in a String', () => { + it('should return NO for any empty string', () => { + expect(hackerrankInString('')).to.equal('NO'); + }); - it("should return YES for an exact match", () => { - expect(hackerrankInString("hackerrank")).to.equal("YES"); - }); + it('should return YES for an exact match', () => { + expect(hackerrankInString('hackerrank')).to.equal('YES'); + }); - describe("should return YES inputs containing hackerrank", () => { - it("hereiamstackerrank", () => - expect(hackerrankInString("hereiamstackerrank")).to.equal("YES")); - it("hhaacckkekraraannk", () => - expect(hackerrankInString("hhaacckkekraraannk")).to.equal("YES")); - }); - describe("should return NO for inputs that don't contain hackerrank", () => { - it("hackerworld", () => - expect(hackerrankInString("hackerworld")).to.equal("NO")); - it("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt", () => - expect( - hackerrankInString("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt") - ).to.equal("NO")); - }); + describe('should return YES inputs containing hackerrank', () => { + it('hereiamstackerrank', () => expect(hackerrankInString('hereiamstackerrank')).to.equal('YES')); + it('hhaacckkekraraannk', () => expect(hackerrankInString('hhaacckkekraraannk')).to.equal('YES')); + }); + describe("should return NO for inputs that don't contain hackerrank", () => { + it('hackerworld', () => expect(hackerrankInString('hackerworld')).to.equal('NO')); + it('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt', () => expect( + hackerrankInString('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt'), + ).to.equal('NO')); + }); }); diff --git a/test/Strings/repeated-string.test.js b/test/Strings/repeated-string.test.js index 7003391..0dd8a47 100644 --- a/test/Strings/repeated-string.test.js +++ b/test/Strings/repeated-string.test.js @@ -1,25 +1,25 @@ -const repeatedString = require("../../src/Strings/repeated-string"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const repeatedString = require('../../src/Strings/repeated-string'); -describe("Repeated String", () => { - it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { - expect(repeatedString("aba", 10)).to.eq(7); - }); +describe('Repeated String', () => { + it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { + expect(repeatedString('aba', 10)).to.eq(7); + }); - it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { - expect(repeatedString("aaaaaa", 1)).to.eq(1); - }); + it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { + expect(repeatedString('aaaaaa', 1)).to.eq(1); + }); - it("should return n if input string is 'a'", () => { - expect(repeatedString("a", 100000)).to.eq(100000); - expect(repeatedString("a", 300)).to.eq(300); - expect(repeatedString("a", 5)).to.eq(5); - }); + it("should return n if input string is 'a'", () => { + expect(repeatedString('a', 100000)).to.eq(100000); + expect(repeatedString('a', 300)).to.eq(300); + expect(repeatedString('a', 5)).to.eq(5); + }); - it("should return 0 if the input string does not contain 'a'", () => { - expect(repeatedString("test", 20)).to.eq(0); - expect(repeatedString("bbbb", 7)).to.eq(0); - expect(repeatedString("cdcdcd", 5)).to.eq(0); - }); + it("should return 0 if the input string does not contain 'a'", () => { + expect(repeatedString('test', 20)).to.eq(0); + expect(repeatedString('bbbb', 7)).to.eq(0); + expect(repeatedString('cdcdcd', 5)).to.eq(0); + }); }); diff --git a/test/Strings/strong-password.test.js b/test/Strings/strong-password.test.js index f9fec61..4e70cfc 100644 --- a/test/Strings/strong-password.test.js +++ b/test/Strings/strong-password.test.js @@ -1,26 +1,19 @@ -const passwordStrengthMinimumNumber = require("../../src/Strings/strong-password"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const passwordStrengthMinimumNumber = require('../../src/Strings/strong-password'); -describe("Strong Password", () => { - it("returns 6 for empty string", () => - expect(passwordStrengthMinimumNumber(0, "")).to.equal(6)); +describe('Strong Password', () => { + it('returns 6 for empty string', () => expect(passwordStrengthMinimumNumber(0, '')).to.equal(6)); - it("returns 3 with password length of 3", () => - expect(passwordStrengthMinimumNumber(3, "Ab1")).to.equal(3)); + it('returns 3 with password length of 3', () => expect(passwordStrengthMinimumNumber(3, 'Ab1')).to.equal(3)); - it("returns 3 with missing special character, number and uppercase letter", () => - expect(passwordStrengthMinimumNumber(3, "longenough")).to.equal(3)); + it('returns 3 with missing special character, number and uppercase letter', () => expect(passwordStrengthMinimumNumber(3, 'longenough')).to.equal(3)); - it("returns 1 with missing number", () => - expect(passwordStrengthMinimumNumber(11, "#HackerRank")).to.equal(1)); + it('returns 1 with missing number', () => expect(passwordStrengthMinimumNumber(11, '#HackerRank')).to.equal(1)); - it("returns 1 with missing special character", () => - expect(passwordStrengthMinimumNumber(11, "1HackerRank")).to.equal(1)); + it('returns 1 with missing special character', () => expect(passwordStrengthMinimumNumber(11, '1HackerRank')).to.equal(1)); - it("returns 1 with missing uppercase letter", () => - expect(passwordStrengthMinimumNumber(12, "#1hackerrank")).to.equal(1)); + it('returns 1 with missing uppercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1hackerrank')).to.equal(1)); - it("returns 1 with missing lowercase letter", () => - expect(passwordStrengthMinimumNumber(12, "#1HACKERRANK")).to.equal(1)); + it('returns 1 with missing lowercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1HACKERRANK')).to.equal(1)); }); diff --git a/test/Strings/time-conversion.test.js b/test/Strings/time-conversion.test.js index 16ba822..5e940bc 100644 --- a/test/Strings/time-conversion.test.js +++ b/test/Strings/time-conversion.test.js @@ -1,21 +1,21 @@ -const timeConversion = require("../../src/Strings/time-conversion"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const timeConversion = require('../../src/Strings/time-conversion'); -describe("Time Conversion", () => { - it("should convert midnight", () => { - expect(timeConversion("12:00:00AM")).to.eq("00:00:00") - }); +describe('Time Conversion', () => { + it('should convert midnight', () => { + expect(timeConversion('12:00:00AM')).to.eq('00:00:00'); + }); - it("should convert noon", () => { - expect(timeConversion("12:00:00PM")).to.eq("12:00:00") - }); + it('should convert noon', () => { + expect(timeConversion('12:00:00PM')).to.eq('12:00:00'); + }); - it("should convert an AM time", () => { - expect(timeConversion("07:05:45AM")).to.eq("07:05:45") - }); + it('should convert an AM time', () => { + expect(timeConversion('07:05:45AM')).to.eq('07:05:45'); + }); - it("should convert a PM time", () => { - expect(timeConversion("07:05:45PM")).to.eq("19:05:45") - }); -}); \ No newline at end of file + it('should convert a PM time', () => { + expect(timeConversion('07:05:45PM')).to.eq('19:05:45'); + }); +}); From b20d2cca17b4f9117baf701547ce52c350afe04b Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Thu, 28 Oct 2021 01:14:52 +0530 Subject: [PATCH 6/8] Revert "Fix eslint and add eslint to travis" This reverts commit 0f65f54eb350a446fc723e7a6b3ee1c169caf008. --- src/Arrays/2d-array-ds.js | 22 ++--- src/Arrays/apple-and-orange.js | 28 +++--- src/Arrays/array-manipulation.js | 18 ++-- src/Arrays/birthday-cake-candles.js | 24 ++--- src/Arrays/breaking-best-and-worst-records.js | 62 ++++++------- src/Arrays/compare-the-triplets.js | 20 ++--- src/Arrays/diagonal-difference.js | 21 ++--- src/Arrays/jumping-on-the-clouds.js | 31 +++---- src/Arrays/left-rotation.js | 17 ++-- src/Arrays/minimum-swaps-2.js | 35 ++++---- src/Arrays/newyear-chaos.js | 36 ++++---- src/Arrays/sock-merchant.js | 36 ++++---- src/Data Structures/cycle-detection.js | 39 ++++---- .../reverse-doubly-linked-list.js | 85 +++++++++--------- .../count-triplet.js | 37 ++++---- .../custom-hashmap.js | 40 ++++----- .../frequency-queries.js | 58 ++++++------ .../game-of-thrones.js | 14 +-- src/Dictionaries and Hashmaps/ransom-note.js | 71 ++++++++------- .../sherlock-and-anagrams.js | 32 +++---- src/Dictionaries and Hashmaps/two-strings.js | 25 +++--- src/Numbers/grading.js | 27 +++--- src/Numbers/kangaroo.js | 44 ++++----- src/Numbers/plus-minus.js | 34 +++---- src/Numbers/staircase.js | 8 +- src/Sorting/bubble-sort.js | 30 +++---- src/Sorting/mark-and-toys.js | 29 +++--- src/Sorting/mini-max-sum.js | 14 +-- src/Strings/alternating-characters.js | 26 +++--- src/Strings/counting-valleys.js | 34 +++---- src/Strings/hackerrank-in-string.js | 16 ++-- src/Strings/making-anagrams.js | 75 ++++++++-------- src/Strings/repeated-string.js | 16 ++-- src/Strings/sherlock-and-the-valid-string.js | 61 ++++++------- src/Strings/strong-password.js | 32 ++++--- src/Strings/time-conversion.js | 31 +++---- test/Arrays/birthday-cake-candles.test.js | 46 +++++----- test/Arrays/left-rotation.test.js | 34 +++---- test/Data Structures/cycle-detection.test.js | 90 +++++++++---------- .../reverse-doubly-linked-list.test.js | 45 +++++----- test/Numbers/plus-minus.test.js | 26 +++--- test/Strings/hackerrank-in-string.test.js | 44 ++++----- test/Strings/repeated-string.test.js | 40 ++++----- test/Strings/strong-password.test.js | 29 +++--- test/Strings/time-conversion.test.js | 34 +++---- 45 files changed, 833 insertions(+), 783 deletions(-) diff --git a/src/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js index 6bb6e73..1e5a28e 100644 --- a/src/Arrays/2d-array-ds.js +++ b/src/Arrays/2d-array-ds.js @@ -4,14 +4,14 @@ Score: 15 Link: https://www.hackerrank.com/challenges/2d-array/ */ -module.exports = function hourglassSum(arr) { - let sum = -1000; - let max = sum; - for (let i = 0; i < 4; i++) { - for (let j = 0; j < 4; j++) { - sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; - if (sum > max) max = sum; - } - } - console.log(max); -}; +function hourglassSum(arr) { + var sum = -1000 + let max = sum + for(let i = 0 ; i<4;i++){ + for(let j = 0 ; j<4; j++){ + sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] + if(sum>max) max = sum + } + } + console.log(max) +} diff --git a/src/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js index ca0011d..ffaf16a 100644 --- a/src/Arrays/apple-and-orange.js +++ b/src/Arrays/apple-and-orange.js @@ -5,20 +5,22 @@ Link: https://www.hackerrank.com/challenges/apple-and-orange */ +function countApplesAndOranges(s, t, a, b, apples, oranges) { + countFruitsFallInsideHome(apples, s - a, t - a); + countFruitsFallInsideHome(oranges, s - b, t - b); +} + + function countFruitsFallInsideHome(fruits, startHome, EndHome) { - let counter = 0; - fruits.forEach((fruit) => { - if (fruit >= startHome && fruit <= EndHome) { - counter++; - } - return counter; - }); + let counter = 0; + fruits.forEach(fruit => { + if (fruit >= startHome && fruit <= EndHome) { + return counter++; + } + }); - return console.log(counter); -} -function countApplesAndOranges(s, t, a, b, apples, oranges) { - countFruitsFallInsideHome(apples, s - a, t - a); - countFruitsFallInsideHome(oranges, s - b, t - b); + return console.log(counter); } -countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1], [5 - 6]); +countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1] , [5 -6]); + diff --git a/src/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js index a04ae2b..45eaf1d 100644 --- a/src/Arrays/array-manipulation.js +++ b/src/Arrays/array-manipulation.js @@ -5,14 +5,14 @@ Link: https://www.hackerrank.com/challenges/crush/problem */ -module.exports = function arrayManipulation(n, queries) { - const arr = Array(n).fill(0); +function arrayManipulation(n, queries) { + let arr = Array(n).fill(0); - for (let a = 0; a < queries.length; a++) { - for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { - arr[index] += queries[a][2]; - } - } + for (let a = 0; a < queries.length; a++) { + for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { + arr[index] += queries[a][2]; + } + } - return Math.max(...arr); -}; + return Math.max(...arr); +} diff --git a/src/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js index 674311e..35ed0d7 100644 --- a/src/Arrays/birthday-cake-candles.js +++ b/src/Arrays/birthday-cake-candles.js @@ -6,16 +6,16 @@ */ module.exports = function birthdayCakeCandles(arr) { - let tallestCandle = 0; - let candlesCounter = 0; - for (let index = 0; index < arr.length; index++) { - if (arr[index] > tallestCandle) { - tallestCandle = arr[index]; - candlesCounter = 1; - } else if (arr[index] === tallestCandle) { - candlesCounter++; - } - } + let tallestCandle = 0; + let candlesCounter = 0; + for (let index = 0; index < arr.length; index++) { + if (arr[index] > tallestCandle) { + tallestCandle = arr[index]; + candlesCounter = 1; + } else if (arr[index] === tallestCandle) { + candlesCounter++; + } + } - return candlesCounter; -}; + return candlesCounter; +} diff --git a/src/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js index 9df7f33..1afad77 100644 --- a/src/Arrays/breaking-best-and-worst-records.js +++ b/src/Arrays/breaking-best-and-worst-records.js @@ -6,35 +6,37 @@ */ function breakingRecords(scores) { - const counters = { - min: 0, - max: 0, - }; - - const values = { - min: 0, - max: 0, - }; - let isDefaultSet = false; - - scores.forEach((score) => { - if (!isDefaultSet) { - values.min = score; - values.max = score; - isDefaultSet = true; - return; - } - - if (score > values.max) { - values.max = score; - counters.max++; - } else if (score < values.min) { - values.min = score; - counters.min++; - } - }); - - return [counters.max, counters.min]; + + let counters = { + min: 0, + max: 0 + }; + + let values = { + min: 0, + max: 0 + } + let isDefaultSet = false; + + scores.forEach(score => { + if (!isDefaultSet) { + values.min = score; + values.max = score; + isDefaultSet = true; + return ; + } + + if (score > values.max) { + values.max = score; + counters.max++; + } else if (score < values.min) { + values.min = score; + counters.min++; + } + }) + + return [counters.max, counters.min]; + } -breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]); +breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]) diff --git a/src/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js index b542423..75d6007 100644 --- a/src/Arrays/compare-the-triplets.js +++ b/src/Arrays/compare-the-triplets.js @@ -6,16 +6,16 @@ Link: https://www.hackerrank.com/challenges/compare-the-triplets/problem */ function compareTriplets(a, b) { - const points = [0, 0]; - for (let index = 0; index < a.length; index++) { - if (a[index] > b[index]) { - points[0] += 1; - } else if (a[index] < b[index]) { - points[1] += 1; - } - } + let points = [0, 0]; + for (let index = 0; index < a.length; index++){ + if (a[index] > b[index]) { + points[0] += 1; + } else if (a[index] < b[index]) { + points[1] += 1; + } + } - return points; + return points; } -console.log(compareTriplets([5, 6, 7], [3, 6, 10])); +console.log(compareTriplets([5, 6, 7], [3, 6, 10])) diff --git a/src/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js index 5304e9e..336b05d 100644 --- a/src/Arrays/diagonal-difference.js +++ b/src/Arrays/diagonal-difference.js @@ -1,3 +1,4 @@ + /* Title:Diagonal Difference Difficulty: Easy @@ -6,16 +7,16 @@ */ function diagonalDifference(arr) { - let leftToRight = 0; - let rightToLeft = 0; - let tmpLength = arr.length; - for (let i = 0; i < arr.length; i++) { - leftToRight += arr[i][i]; - rightToLeft += arr[i][--tmpLength]; - } + let leftToRight = 0; + let rightToLeft = 0; + let tmpLength = arr.length; + for (let i = 0; i < arr.length; i++){ + leftToRight += arr[i][i]; + rightToLeft += arr[i][--tmpLength]; + } - return Math.abs(leftToRight - rightToLeft); + return Math.abs(leftToRight - rightToLeft); } -const input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]; -console.log(diagonalDifference(input)); +let input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] +console.log(diagonalDifference(input)) diff --git a/src/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js index 0488a2f..9f5c7d1 100644 --- a/src/Arrays/jumping-on-the-clouds.js +++ b/src/Arrays/jumping-on-the-clouds.js @@ -5,19 +5,20 @@ Link: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ */ -module.exports = function jumpingOnClouds(c) { - let jump = 0; - for (let i = 0; i < c.length;) { - if (c[i + 2] === 0) { - jump++; - i += 2; - } else if (c[i + 1] === 0) { - jump++; - i += 1; - } else { - i++; - } - } +function jumpingOnClouds(c) { - return jump; -}; + let jump = 0; + for (let i = 0; i < c.length;){ + if (c[i + 2] == 0) { + jump++; + i += 2; + } else if (c[i + 1] == 0) { + jump++; + i += 1; + } else { + i++; + } + } + + return jump; +} diff --git a/src/Arrays/left-rotation.js b/src/Arrays/left-rotation.js index 7881ba7..17ed7de 100644 --- a/src/Arrays/left-rotation.js +++ b/src/Arrays/left-rotation.js @@ -6,13 +6,14 @@ */ module.exports = function rotLeft(a, d) { - if (!a.length) { - return []; - } - for (let i = 0; i < d; i++) { - a.push(a.shift()); - } + if(!a.length){ + return [] + } - return a; -}; + for (let i = 0; i < d; i++) { + a.push(a.shift()); + } + + return a; +} diff --git a/src/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js index 95c93fc..c382556 100644 --- a/src/Arrays/minimum-swaps-2.js +++ b/src/Arrays/minimum-swaps-2.js @@ -5,21 +5,22 @@ Link: https://www.hackerrank.com/challenges/minimum-swaps-2 */ -module.exports = function minimumSwaps(arr) { - const origArray = arr.slice(0); - const sortedArray = arr.sort((a, b) => a - b); - let numberOfSwap = 0; - for (let i = 0; i < origArray.length; i++) { - if (origArray[i] !== sortedArray[i]) { - for (let j = i + 1; j < origArray.length; j++) { - if (origArray[j] === sortedArray[i]) { - [origArray[i], origArray[j]] = [origArray[j], origArray[i]]; - numberOfSwap++; - break; - } - } - } - } - return numberOfSwap; -}; +function minimumSwaps(arr) { + var origArray = arr.slice(0); + var sortedArray = arr.sort((a,b) => a-b); + let numberOfSwap = 0; + for (var i = 0; i < origArray.length; i++) { + if (origArray[i] != sortedArray[i]) { + for (var j = i + 1; j < origArray.length; j++) { + if (origArray[j] === sortedArray[i]) { + [origArray[i], origArray[j]] = [origArray[j], origArray[i]] + numberOfSwap++ + break; + } + } + } + } + + return numberOfSwap; +} diff --git a/src/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js index 08eb21a..0ae6270 100644 --- a/src/Arrays/newyear-chaos.js +++ b/src/Arrays/newyear-chaos.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/new-year-chaos/ */ -module.exports = function minimumBribes(q) { - let swaps = 0; - let min = q.length; - for (let i = q.length - 1; i >= 0; i--) { - if (q[i] - i > 3) { - return 'Too chaotic'; - } - if (q[i] > i + 1) { - swaps += (q[i] - (i + 1)); - } else if (min > q[i]) { - min = q[i]; - } else if (q[i] !== min) { - swaps++; - } - } +function minimumBribes(q) { + let swaps = 0; + let min = q.length; + for (var i = q.length -1 ; i >= 0; i--) { + if (q[i] - i > 3) { + return `Too chaotic`; + } + if (q[i] > i + 1) { + swaps += (q[i] - (i + 1)); + } else { + if (min > q[i]) { + min = q[i]; + } else if (q[i] != min) { + swaps++; + } + } + } - return swaps; -}; + return swaps; +} diff --git a/src/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js index c75cf50..e865834 100644 --- a/src/Arrays/sock-merchant.js +++ b/src/Arrays/sock-merchant.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/sock-merchant */ -module.exports = function sockMerchant(n, ar) { - const tmpArr = []; - let counter = 0; - ar.map((value) => { - if (tmpArr.includes(value)) { - const index = tmpArr.indexOf(value); - if (index > -1) { - tmpArr.splice(index, 1); - } - counter++; - } else { - tmpArr.push(value); - } - return value; - }); - return counter; -}; +function sockMerchant(n, ar) { + let tmpArr = []; + let counter = 0; + ar.map(value => { + if (tmpArr.includes(value)) { + var index = tmpArr.indexOf(value); + if (index > -1) { + tmpArr.splice(index, 1); + } + counter++; + } else { + tmpArr.push(value); + } + + }) + + return counter; + +} diff --git a/src/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js index 46ee960..5bd280a 100644 --- a/src/Data Structures/cycle-detection.js +++ b/src/Data Structures/cycle-detection.js @@ -6,31 +6,30 @@ */ function hasCycle(head) { - if (head === null || head.next === null || head.next.next === null) return false; // edge cases - let hare = head; - let tortoise = head; - do { - hare = hare.next.next; // 'hare' moves twice per tick - tortoise = tortoise.next; // 'tortoise' moves once per tick - } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); - return hare === tortoise; + if (head === null || head.next === null || head.next.next === null) return false; // edge cases + let hare = head; + let tortoise = head; + do { + hare = hare.next.next; // 'hare' moves twice per tick + tortoise = tortoise.next; // 'tortoise' moves once per tick + } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); + return hare === tortoise; } // NODE CLASS class Node { - constructor(data) { - this.data = data; - this.next = null; - } - - insert(data) { - this.next = new Node(data); - return this.next; // for chaining - } + constructor (data) { + this.data = data; + this.next = null; + } + insert (data) { + this.next = new Node(data); + return this.next; // for chaining + } } module.exports = { - hasCycle, - Node, -}; + hasCycle, + Node, +}; \ No newline at end of file diff --git a/src/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js index 3d4ae7d..04dcde3 100644 --- a/src/Data Structures/reverse-doubly-linked-list.js +++ b/src/Data Structures/reverse-doubly-linked-list.js @@ -1,53 +1,56 @@ +'use strict'; /* Title: Reverse a doubly linked list Difficulty: Easy Score: 5 Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem */ -class DoublyLinkedListNode { - constructor(nodeData) { - this.data = nodeData; - this.next = null; - this.prev = null; - } -} -class DoublyLinkedList { - constructor() { - this.head = null; - this.tail = null; - } - - insertNode(nodeData) { - const node = new DoublyLinkedListNode(nodeData); - - if (this.head == null) { - this.head = node; - } else { - this.tail.next = node; - node.prev = this.tail; - } - - this.tail = node; - } -} function reverse(head) { - while (head.next) { - head = head.next; - } - - const newList = new DoublyLinkedList(); - - while (head) { - newList.insertNode(head.data); - head = head.prev; - } - return newList.head; + while (head.next) { + head = head.next + } + + const newList = new DoublyLinkedList(); + + while (head) { + newList.insertNode(head.data); + head = head.prev + } + return newList.head } -module.exports = { - reverse, - DoublyLinkedList, - DoublyLinkedListNode, +class DoublyLinkedListNode { + constructor(nodeData) { + this.data = nodeData; + this.next = null; + this.prev = null; + } +}; + +class DoublyLinkedList { + constructor() { + this.head = null; + this.tail = null; + } + + insertNode(nodeData) { + let node = new DoublyLinkedListNode(nodeData); + + if (this.head == null) { + this.head = node; + } else { + this.tail.next = node; + node.prev = this.tail; + } + + this.tail = node; + } }; + +module.exports = { + reverse, + DoublyLinkedList, + DoublyLinkedListNode +} diff --git a/src/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js index 38656ad..ac8d48c 100644 --- a/src/Dictionaries and Hashmaps/count-triplet.js +++ b/src/Dictionaries and Hashmaps/count-triplet.js @@ -6,29 +6,30 @@ */ function countTriplets(arr, r) { - const second = {}; - const third = {}; - let count = 0; - for (let index = 0; index < arr.length; index++) { - const val = arr[index]; + let second = {} + let third = {} + let count = 0; + for (let index = 0; index < arr.length; index++) { - // If value found on third then add it to count - if (third[val]) { - count += third[val]; - } + const val = arr[index]; - // If value found on second , convey it to third + //If value found on third then add it to count + if(third[val]){ + count += third[val]; + } - if (second[val]) { - third[val * r] = third[val * r] + second[val] || second[val]; - } + //If value found on second , convey it to third - // add current element into second value + if(second[val]){ + third[val*r] = third[val*r] + second[val] || second[val]; + } - second[val * r] = second[val * r] + 1 || 1; - } + //add current element into second value - return count; + second[val*r] = second[val*r]+1 || 1; + } + + return count; } -console.log(countTriplets([1, 2, 2, 4], 2)); +console.log(countTriplets([1,2 ,2,4], 2)); diff --git a/src/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js index 4c05db3..c2431ec 100644 --- a/src/Dictionaries and Hashmaps/custom-hashmap.js +++ b/src/Dictionaries and Hashmaps/custom-hashmap.js @@ -5,31 +5,31 @@ Link: - */ class customHashMap { - constructor() { - this.list = []; - } + constructor() { + this.list = []; + } - get(x) { - return this.list[this.hashCode(x)]; - } + get(x) { + return this.list[this.hashCode(x)]; + } - set(x, y) { - this.list[this.hashCode(x)] = y; - } + set(x, y) { + this.list[this.hashCode(x)] = y; + } - static hashCode(str) { - let hash = 0; - if (str.length === 0) return hash; - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash &= hash; // Convert to 32bit integer - } - return hash; - } + hashCode(str) { + let hash = 0; + if (str.length == 0) return hash; + for (let i = 0; i < str.length; i++) { + let char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash = hash & hash; // Convert to 32bit integer + } + return hash; + } } -const m = customHashMap(); +let m = new customHashMap(); m.set('hello', 'world'); console.log(m.get('hello')); diff --git a/src/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js index 40ccb6b..c3f4d5a 100644 --- a/src/Dictionaries and Hashmaps/frequency-queries.js +++ b/src/Dictionaries and Hashmaps/frequency-queries.js @@ -6,40 +6,40 @@ */ function freqQuery(arr) { - const result = []; - const hash = {}; - const freq = []; + const result = []; + const hash = {}; + const freq = []; - for (let i = 0; i < arr.length; i += 1) { - const [action, value] = arr[i]; - const initValue = hash[value] || 0; + for (let i = 0; i < arr.length; i += 1) { + const [action, value] = arr[i]; + const initValue = hash[value] || 0; - if (action === 1) { - hash[value] = initValue + 1; - freq[initValue] = (freq[initValue] || 0) - 1; - freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; - } + if (action === 1) { + hash[value] = initValue + 1; + freq[initValue] = (freq[initValue] || 0) - 1; + freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; + } - if (action === 2 && initValue > 0) { - hash[value] = initValue - 1; - freq[initValue - 1] += 1; - freq[initValue] -= 1; - } + if (action === 2 && initValue > 0) { + hash[value] = initValue - 1; + freq[initValue - 1] += 1; + freq[initValue] -= 1; + } - if (action === 3) result.push(freq[value] > 0 ? 1 : 0); - } + if (action === 3) result.push(freq[value] > 0 ? 1 : 0); + } - return result; + return result; } -const input = [ - [1, 5], - [1, 6], - [3, 2], - [1, 10], - [1, 10], - [1, 6], - [2, 5], - [3, 2], -]; +let input = [ + [1, 5], + [1, 6], + [3, 2], + [1, 10], + [1, 10], + [1, 6], + [2, 5], + [3, 2] + ]; console.log(freqQuery(input)); diff --git a/src/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js index 31e1f31..0d50f1e 100644 --- a/src/Dictionaries and Hashmaps/game-of-thrones.js +++ b/src/Dictionaries and Hashmaps/game-of-thrones.js @@ -6,12 +6,12 @@ */ function gameOfThrones(s) { - const frequencies = {}; - for (const char of s) frequencies[char] = frequencies[char] + 1 || 1; - const oddFrequencies = Object.values(frequencies).filter((frequency) => frequency % 2); - return oddFrequencies.length <= 1 ? 'YES' : 'NO'; + const frequencies = {}; + for (let char of s) frequencies[char] = frequencies[char] + 1 || 1; + let oddFrequencies = Object.values(frequencies).filter(frequency => frequency % 2); + return oddFrequencies.length <= 1 ? 'YES' : 'NO'; } -console.log(gameOfThrones('aaabbbb')); // YES -console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO -console.log(gameOfThrones('cdcdcdcdeeeef')); // YES +console.log(gameOfThrones('aaabbbb')); // YES +console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO +console.log(gameOfThrones('cdcdcdcdeeeef')); // YES \ No newline at end of file diff --git a/src/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js index 2268c69..bf7003a 100644 --- a/src/Dictionaries and Hashmaps/ransom-note.js +++ b/src/Dictionaries and Hashmaps/ransom-note.js @@ -6,48 +6,51 @@ */ class ExtendedMap { - constructor() { - this.map = new Map(); - } - - get(x) { - let value = this.map.get(x); - if (value === 1) { - this.map.delete(x); - return true; - } - - return this.map.set(x, --value); - } - - set(x, y) { - if (this.map.get(x)) { - return this.map.set(x, this.map.get(x) + 1); - } - - return this.map.set(x, y); - } + + constructor(){ + this.map = new Map(); + } + + get(x) { + let value = this.map.get(x); + if (value === 1) { + this.map.delete(x); + return true; + } + + return this.map.set(x, --value); + } + + set(x, y) { + if (this.map.get(x)) { + return this.map.set(x, this.map.get(x) + 1); + } + + return this.map.set(x, y); + } } + function checkMagazine(magazine, note) { - const m = new ExtendedMap(); - for (let i = 0; i < magazine.length; i++) { - m.set(magazine[i], 1); - } + let m = new ExtendedMap() + + for (let i = 0; i < magazine.length; i++) { + m.set(magazine[i], 1) + } - for (let i = 0; i < note.length; i++) { - if (!m.get(note[i])) { - console.log('No'); - return; - } - } + for (let i = 0; i < note.length; i++) { + if (!m.get(note[i])) { + console.log('No'); + return; + }; + } - console.log('Yes'); + console.log('Yes'); } -const magazine = ['give', 'me', 'one', 'grand', 'today', 'night']; -const note = ['give', 'one', 'grand', 'today']; +let magazine = [ 'give', 'me', 'one', 'grand', 'today', 'night' ]; +let note = [ 'give', 'one', 'grand', 'today' ]; console.time('Time Taken'); checkMagazine(magazine, note); diff --git a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js index 8b655d9..138f0db 100644 --- a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js +++ b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js @@ -5,23 +5,23 @@ Link: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ */ function sherlockAndAnagrams(s) { - let count = 0; - const strLength = s.length; // get length - for (let i = 1; i < strLength; i++) { - const found = {}; - for (let j = 0; j + i <= strLength; j++) { - let substr = s.substr(j, i); // device string into substr - substr = substr.split('').sort().join(''); // sort it - if (found[substr]) { - count += found[substr]; // count total - found[substr]++; - } else { - found[substr] = 1; - } - } - } + let count = 0; + let strLength = s.length; //get length + for (let i = 1; i < strLength; i++) { + let found = {}; + for (let j = 0; j + i <= strLength; j++) { + let substr = s.substr(j, i); //device string into substr + substr = substr.split('').sort().join(''); //sort it + if (found[substr]) { + count += found[substr]; //count total + found[substr]++; + } else { + found[substr] = 1; + } + } + } - return count; + return count; } console.log(sherlockAndAnagrams('cdcd')); diff --git a/src/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js index cc1845d..f9f7e3d 100644 --- a/src/Dictionaries and Hashmaps/two-strings.js +++ b/src/Dictionaries and Hashmaps/two-strings.js @@ -6,21 +6,22 @@ */ function twoStrings(s1, s2) { - const m = new Map(); - for (let i = 0; i < s1.length; i++) { - m.set(s1[i], 1); - } + m = new Map(); + for(let i=0; i { - if (grade < 38) { - return grade; - } +function gradingStudents(grades) { + let newGrades = grades.map(grade => { + if (grade < 38) { + return grade; + } - const roundRemainder = grade % 5; + let roundRemainder = grade % 5; - if (roundRemainder === 0 || roundRemainder <= 2) { - return grade; - } + if (roundRemainder === 0 || roundRemainder <= 2) { + return grade; + } - return grade + (5 - roundRemainder); - }); + return grade + (5 - roundRemainder); + }) - return newGrades; -}; + return newGrades; + +} diff --git a/src/Numbers/kangaroo.js b/src/Numbers/kangaroo.js index 90ae9da..06495a1 100644 --- a/src/Numbers/kangaroo.js +++ b/src/Numbers/kangaroo.js @@ -7,26 +7,29 @@ // Solution 1 function kangaroo(x1, v1, x2, v2) { - if ((x2 > x1 && v2 > v1) || v1 === v2) { - return 'NO'; - } + if ((x2 > x1 && v2 > v1) || v1 === v2) { + return 'NO'; + } - let x1Distance = x1; - let x2Distance = x2; + let x1Distance = x1; + let x2Distance = x2; - while (x1Distance !== x2Distance) { - x1Distance += v1; - x2Distance += v2; + while (x1Distance !== x2Distance) { + x1Distance += v1; + x2Distance += v2; - if (x1Distance > x2Distance) { - return 'NO'; - } - } + if (x1Distance > x2Distance) { + return 'NO'; + } + } + + return 'YES'; - return 'YES'; } -// Solution 2 + +//Solution 2 + /* @@ -43,12 +46,11 @@ x1 - x2 / v2 - v1 = y so we can find y with all 4 inputs if it is integer and greater than 0 then both will meet */ -function kangarooSolution2(x1, v1, x2, v2) { - if (x2 > x1 && v2 > v1) { - return 'NO'; - } +function kangaroo(x1, v1, x2, v2) { + if (x2 > x1 && v2 > v1) { + return 'NO' + } - const steps = (x1 - x2) % (v2 - v1); - return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; + let steps = (x1 - x2) % (v2 - v1); + return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; } -module.exports = [kangaroo, kangarooSolution2]; diff --git a/src/Numbers/plus-minus.js b/src/Numbers/plus-minus.js index 164be6c..b754238 100644 --- a/src/Numbers/plus-minus.js +++ b/src/Numbers/plus-minus.js @@ -6,22 +6,22 @@ */ module.exports = function plusMinus(arr) { - const result = { - positive: 0, - negative: 0, - zero: 0, - }; + let result = { + positive: 0, + negative: 0, + zero: 0, + } - const arrLength = arr.length; - for (let index = 0; index < arrLength; index++) { - if (arr[index] === 0) { - ++result.zero; - } else if (arr[index] > 0) { - ++result.positive; - } else { - ++result.negative; - } - } + let arrLength = arr.length; + for (let index = 0; index < arrLength; index++){ + if (arr[index] === 0) { + ++result.zero; + } else if (arr[index] > 0) { + ++result.positive; + } else { + ++result.negative; + } + } - return result; -}; + return result; +} diff --git a/src/Numbers/staircase.js b/src/Numbers/staircase.js index 6a05c07..f09ff35 100644 --- a/src/Numbers/staircase.js +++ b/src/Numbers/staircase.js @@ -6,10 +6,10 @@ */ function staircase(n) { - let tmp = n; - for (let index = 0; index < n; index++) { - console.log(' '.repeat(--tmp) + '#'.repeat(index + 1)); - } + let tmp = n; + for (let index = 0; index < n; index++){ + console.log(' '.repeat(--tmp) + '#'.repeat(index + 1 )); + } } staircase(6); diff --git a/src/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js index 794c249..d6d9c81 100644 --- a/src/Sorting/bubble-sort.js +++ b/src/Sorting/bubble-sort.js @@ -6,22 +6,22 @@ */ function countSwaps(a) { - let isSorted = false; - let counter = 0; - while (!isSorted) { - isSorted = true; - for (let i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - [a[i], a[i + 1]] = [a[i + 1], a[i]]; - counter++; - isSorted = false; - } - } - } + let isSorted = false; + let counter = 0; + while (!isSorted) { + isSorted = true; + for (let i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + [a[i], a[i + 1]] = [a[i + 1], a[i]]; + counter++; + isSorted = false; + } + } + } - console.log(`Array is sorted in ${counter} swaps.`); - console.log(`First Element: ${a[0]}`); - console.log(`Last Element: ${a[a.length - 1]}`); + console.log(`Array is sorted in ${counter} swaps.`); + console.log(`First Element: ${a[0]}`); + console.log(`Last Element: ${a[a.length -1 ]}`); } countSwaps([5, 2, 1]); diff --git a/src/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js index 6741a0d..cabb6db 100644 --- a/src/Sorting/mark-and-toys.js +++ b/src/Sorting/mark-and-toys.js @@ -6,21 +6,20 @@ */ function maximumToys(prices, balance) { - prices = prices.sort((a, b) => a - b); - let toysBought = 0; - console.log(prices); - for (let i = 0; i < prices.length; i++) { - if (balance >= prices[i]) { - toysBought++; - balance -= prices[i]; - } else { - break; - } - } - return toysBought; + prices = prices.sort((a, b) => a - b) + let toysBought = 0; + console.log(prices); + for (let i = 0; i < prices.length; i++){ + if (balance >= prices[i]) { + toysBought++; + balance -= prices[i]; + } else { + break; + } + } + return toysBought; + } -const arr = [33324560, 77661073, 31948330, - 21522343, 97176507, 5724692, 24699815, - 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; +let arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; console.log(maximumToys(arr, 100000)); diff --git a/src/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js index 79d6224..83bde36 100644 --- a/src/Sorting/mini-max-sum.js +++ b/src/Sorting/mini-max-sum.js @@ -6,14 +6,14 @@ */ function miniMaxSum(arr) { - const sum = [0, 0]; - arr = arr.sort((a, b) => a - b); - for (let i = 0; i < 4; i++) { - sum[0] += arr[i]; - sum[1] += arr[arr.length - (i + 1)]; - } + let sum = [0, 0]; + arr = arr.sort((a, b) => { return a - b }); + for (let i = 0; i < 4; i++){ + sum[0] += arr[i]; + sum[1] += arr[arr.length - (i+1)]; + } - console.log(sum[0], sum[1]); + console.log(sum[0], sum[1]); } miniMaxSum(1, 2, 3, 4, 5); diff --git a/src/Strings/alternating-characters.js b/src/Strings/alternating-characters.js index 3fbcb1a..b02de77 100644 --- a/src/Strings/alternating-characters.js +++ b/src/Strings/alternating-characters.js @@ -6,22 +6,22 @@ */ function alternatingCharacters(string) { - let prev = ''; - let counter = 0; - for (let index = 0; index < string.length; index++) { - if (!prev) { - prev = string[index]; - continue; - } + let prev = ''; + let counter = 0; + for (let index = 0; index < string.length; index++) { + if(!prev){ + prev = string[index]; + continue; + } - if (prev === string[index]) { - counter++; - } + if(prev === string[index]){ + counter++; + } - prev = string[index]; - } + prev = string[index]; + } - return counter; + return counter; } console.log(alternatingCharacters('BBBBB')); diff --git a/src/Strings/counting-valleys.js b/src/Strings/counting-valleys.js index b8c21eb..dbb44ae 100644 --- a/src/Strings/counting-valleys.js +++ b/src/Strings/counting-valleys.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/counting-valleys */ -module.exports = function countingValleys(n, s) { - let currentValley = 0; - let count = 0; - for (let i = 0; i < n; i++) { - if (s[i] === 'U') { - currentValley++; - } - if (s[i] === 'D') { - currentValley--; - } +function countingValleys(n, s) { + let currentValley = 0; + let count = 0; + for (let i = 0; i < n; i++) { - if (currentValley === 0 && s[i] === 'U') { - count++; - } - } + if (s[i] === 'U') { + currentValley++; + } + if (s[i] === 'D') { + currentValley--; + } - return count; -}; + if (currentValley == 0 && s[i] === 'U') { + count++; + } + } + + return count; + +} diff --git a/src/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js index 2564590..1e8ebbd 100644 --- a/src/Strings/hackerrank-in-string.js +++ b/src/Strings/hackerrank-in-string.js @@ -6,12 +6,12 @@ */ module.exports = function hackerrankInString(s) { - const mask = Array.from('hackerrank'); - for (let i = 0; i < s.length; i++) { - const currentChar = s.charAt(i); - if (mask[0] === currentChar) { - mask.shift(); - } - } - return mask.length === 0 ? 'YES' : 'NO'; + const mask = Array.from("hackerrank"); + for (let i = 0; i < s.length; i++) { + const currentChar = s.charAt(i); + if (mask[0] === currentChar) { + mask.shift(); + } + } + return mask.length === 0 ? "YES" : "NO"; }; diff --git a/src/Strings/making-anagrams.js b/src/Strings/making-anagrams.js index ffc8d75..4de1579 100644 --- a/src/Strings/making-anagrams.js +++ b/src/Strings/making-anagrams.js @@ -4,42 +4,47 @@ Score: 25/ Link: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_r=internal-search */ + + +function makeAnagram(string1, string2){ + string1 = count(string1); + string2 = count(string2); + return findDiff(string1, string2); +} + function count(a) { - const arr = a.split('').sort(); - const counter = {}; - arr.forEach((value) => { - if (counter[value] !== undefined) { - counter[value] += 1; - } else { - counter[value] = 1; - } - }); - - return counter; + let arr = a.split('').sort(); + let counter = {}; + arr.forEach(value => { + if (counter[value] !== undefined) { + counter[value] += 1; + } else { + counter[value] = 1; + } + }) + + return counter; } + function findDiff(arr1, arr2) { - let removeCount = 0; - - for (const key in arr1) { - if (!arr2[key]) { - removeCount += arr1[key]; - } else { - removeCount += Math.abs(arr2[key] - arr1[key]); - } - } - - for (const key in arr2) { - if (!arr1[key]) { - removeCount += arr2[key]; - } - } - return removeCount; -} -function makeAnagram(string1, string2) { - string1 = count(string1); - string2 = count(string2); - return findDiff(string1, string2); + let removeCount = 0; + + for (let key in arr1) { + if (!arr2[key]) { + removeCount += arr1[key]; + } else { + removeCount += Math.abs(arr2[key] - arr1[key]); + } + } + + for (let key in arr2) { + if (!arr1[key]) { + removeCount += arr2[key]; + } + } + return removeCount; } -const a = 'fcrxzwscanmligyxyvym'; -const b = 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'; -console.log(makeAnagram(a, b)); + +let a = "fcrxzwscanmligyxyvym"; +let b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; +console.log(makeAnagram(a,b )); diff --git a/src/Strings/repeated-string.js b/src/Strings/repeated-string.js index 6e71159..4497df6 100644 --- a/src/Strings/repeated-string.js +++ b/src/Strings/repeated-string.js @@ -6,11 +6,11 @@ */ module.exports = function repeatedString(s, n) { - const initialCount = s.split('a').length - 1; - const cocent = Math.floor(n / s.length); - let total = cocent * initialCount; - const remainder = n % s.length; - const remaindLetter = s.slice(0, remainder); - total += remaindLetter.split('a').length - 1; - return total; -}; + let initialCount = s.split('a').length - 1; + let cocent = Math.floor(n / s.length); + let total = cocent * initialCount; + let remainder = n % s.length; + let remaindLetter = s.slice(0, remainder); + total += remaindLetter.split('a').length - 1; + return total; +} diff --git a/src/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js index d786906..5846fcf 100644 --- a/src/Strings/sherlock-and-the-valid-string.js +++ b/src/Strings/sherlock-and-the-valid-string.js @@ -6,35 +6,36 @@ */ function isValid(string) { - const counter = {}; - - const arr = string.split('').sort(); - let smallValue = 0; - let allowedTimes = 0; - arr.forEach((element) => { - counter[element] = counter[element] === undefined ? 1 : counter[element] + 1; - }); - - for (const key in counter) { - if (smallValue === 0) { - smallValue = counter[key]; - continue; - } - - if (smallValue !== counter[key]) { - if (counter[key] === 1) { - allowedTimes += 1; - } else { - allowedTimes += Math.abs(smallValue - counter[key]); - } - } - - if (allowedTimes > 1) { - break; - } - } - - return !(allowedTimes > 1); + let counter = {}; + + let arr = string.split('').sort(); + let smallValue = 0; + let allowedTimes = 0; + arr.forEach(element => { + counter[element] = counter[element] === undefined ? 1 : counter[element]+1; + }); + + for(let key in counter){ + if(smallValue === 0){ + smallValue = counter[key]; + continue ; + } + + if(smallValue !== counter[key]){ + if(counter[key] === 1){ + allowedTimes += 1; + } else { + allowedTimes += Math.abs(smallValue - counter[key]); + } + } + + if(allowedTimes > 1){ + break; + } + } + + return allowedTimes > 1 ? false : true; } -console.log(isValid('abcdefghhgfedecba')); + +console.log(isValid("abcdefghhgfedecba")); diff --git a/src/Strings/strong-password.js b/src/Strings/strong-password.js index fa54fb6..d3fd7c0 100644 --- a/src/Strings/strong-password.js +++ b/src/Strings/strong-password.js @@ -6,21 +6,27 @@ */ module.exports = function passwordStrengthMinimumNumber(n, password) { - const STRONG_LENGTH = 6; - const missingChars = STRONG_LENGTH - n; - let score = 0; + const STRONG_LENGTH = 6; + const missingChars = STRONG_LENGTH - n; + let score = 0; - const passwordAsArray = Array.from(password); + const passwordAsArray = Array.from(password); - const hasNumber = passwordAsArray.some((char) => '0123456789'.includes(char)); - const hasLowerCase = passwordAsArray.some((char) => 'abcdefghijklmnopqrstuvwxyz'.includes(char)); - const hasUpperCase = passwordAsArray.some((char) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(char)); - const hasSpecialChar = passwordAsArray.some((char) => '!@#$%^&*()-+'.includes(char)); + const hasNumber = passwordAsArray.some(char => "0123456789".includes(char)); + const hasLowerCase = passwordAsArray.some(char => + "abcdefghijklmnopqrstuvwxyz".includes(char) + ); + const hasUpperCase = passwordAsArray.some(char => + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(char) + ); + const hasSpecialChar = passwordAsArray.some(char => + "!@#$%^&*()-+".includes(char) + ); - if (!hasNumber) score++; - if (!hasLowerCase) score++; - if (!hasUpperCase) score++; - if (!hasSpecialChar) score++; + if (!hasNumber) score++; + if (!hasLowerCase) score++; + if (!hasUpperCase) score++; + if (!hasSpecialChar) score++; - return Math.max(score, missingChars); + return Math.max(score, missingChars); }; diff --git a/src/Strings/time-conversion.js b/src/Strings/time-conversion.js index dc86243..6cabfbc 100644 --- a/src/Strings/time-conversion.js +++ b/src/Strings/time-conversion.js @@ -5,23 +5,24 @@ Link: https://www.hackerrank.com/challenges/time-conversion/ */ + module.exports = function timeConversion(time) { - const cycle = time.substring(time.length - 2, time.length); - const timeWithoutCycle = time.substring(0, time.length - 2); - const timeArr = timeWithoutCycle.split(':'); + let cycle = time.substring(time.length - 2, time.length); + let timeWithoutCycle = time.substring(0, time.length - 2); + let timeArr = timeWithoutCycle.split(':'); - if (cycle === 'AM') { - if (timeArr[0] !== '12') { - return timeWithoutCycle; - } + if (cycle === 'AM') { + if (timeArr[0] != 12) { + return timeWithoutCycle; + } - timeArr[0] = '00'; - return timeArr.join(':'); - } + timeArr[0] = '00'; + return timeArr.join(':'); + } - if (timeArr[0] !== '12') { - timeArr[0] = parseInt(timeArr[0], 10) + 12; - } + if (timeArr[0] != 12) { + timeArr[0] = parseInt(timeArr[0]) + 12; + } - return timeArr.join(':'); -}; + return timeArr.join(':') +} diff --git a/test/Arrays/birthday-cake-candles.test.js b/test/Arrays/birthday-cake-candles.test.js index 506cc68..5d43aba 100644 --- a/test/Arrays/birthday-cake-candles.test.js +++ b/test/Arrays/birthday-cake-candles.test.js @@ -1,28 +1,28 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const birthdayCakeCandles = require('../../src/Arrays/birthday-cake-candles'); +const birthdayCakeCandles = require("../../src/Arrays/birthday-cake-candles"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Birthday Cake Candles', () => { - it('returns 0 for empty array', () => { - expect(birthdayCakeCandles([])).to.equal(0); - }); +describe("Birthday Cake Candles", () => { + it("returns 0 for empty array", () => { + expect(birthdayCakeCandles([])).to.equal(0); + }); - it('returns 1 if there is only one candle', () => { - expect(birthdayCakeCandles([1])).to.equal(1); - expect(birthdayCakeCandles([2])).to.equal(1); - expect(birthdayCakeCandles([3])).to.equal(1); - }); + it("returns 1 if there is only one candle", () => { + expect(birthdayCakeCandles([1])).to.equal(1); + expect(birthdayCakeCandles([2])).to.equal(1); + expect(birthdayCakeCandles([3])).to.equal(1); + }); - it('returns 2 if there are two candles with the same height', () => { - expect(birthdayCakeCandles([1, 1])).to.equal(2); - expect(birthdayCakeCandles([2, 2])).to.equal(2); - expect(birthdayCakeCandles([3, 3])).to.equal(2); - }); + it("returns 2 if there are two candles with the same height", () => { + expect(birthdayCakeCandles([1, 1])).to.equal(2); + expect(birthdayCakeCandles([2, 2])).to.equal(2); + expect(birthdayCakeCandles([3, 3])).to.equal(2); + }); - it('returns correct amount for array with different sized candles', () => { - expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); - expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); - expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); - expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); - }); + it("returns correct amount for array with different sized candles", () => { + expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); + expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); + expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); + expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); + }); }); diff --git a/test/Arrays/left-rotation.test.js b/test/Arrays/left-rotation.test.js index 0965ab2..2a4e66a 100644 --- a/test/Arrays/left-rotation.test.js +++ b/test/Arrays/left-rotation.test.js @@ -1,20 +1,22 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const leftRotation = require('../../src/Arrays/left-rotation'); +const leftRotation = require('../../src/Arrays/left-rotation') +const { describe, it } = require('mocha') +const { expect } = require('chai') describe('Left Rotation', () => { - it('should work for any empty array', () => { - expect(leftRotation([], 10)).to.deep.equal([]); - }); - it('should work for a 1 element array', () => { - const original = [1]; - expect(leftRotation(original, 10)).to.deep.equal(original); - }); + it('should work for any empty array', () => { + expect(leftRotation([], 10)).to.deep.equal([]) + }) - it('should work for multiple elements', () => { - const original = 'ABCDEF'.split(''); - const expected = 'DEFABC'.split(''); - expect(leftRotation(original, 3)).to.deep.equal(expected); - }); -}); + it('should work for a 1 element array', () => { + const original = [1] + expect(leftRotation(original, 10)).to.deep.equal(original) + }) + + it('should work for multiple elements', () => { + const original = "ABCDEF".split('') + const expected = "DEFABC".split('') + expect(leftRotation(original, 3)).to.deep.equal(expected) + }) + +}) diff --git a/test/Data Structures/cycle-detection.test.js b/test/Data Structures/cycle-detection.test.js index 24bbb2e..32fdcb7 100644 --- a/test/Data Structures/cycle-detection.test.js +++ b/test/Data Structures/cycle-detection.test.js @@ -1,54 +1,54 @@ +const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); const { describe, it } = require('mocha'); const { expect } = require('chai'); -const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); describe('Cycle Detection', () => { - it('should detect a cycle in a regular linked list', () => { - const test1 = new Node(1); - const tail1 = test1.insert(2) // tail1 === Node #8 - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - const connection1 = test1.next.next.next; // connection1 === Node #4 - tail1.next = connection1; - expect(hasCycle(test1)).to.equal(true); - }); + it('should detect a cycle in a regular linked list', () => { + const test1 = new Node(1); + const tail1 = test1.insert(2) // tail1 === Node #8 + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + const connection1 = test1.next.next.next; // connection1 === Node #4 + tail1.next = connection1; + expect(hasCycle(test1)).to.equal(true); + }); - it('should return false when the end of the list points to null', () => { - const test2 = new Node(1); - test2.insert(2) - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - expect(hasCycle(test2)).to.equal(false); - }); + it('should return false when the end of the list points to null', () => { + const test2 = new Node(1); + test2.insert(2) + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + expect(hasCycle(test2)).to.equal(false); + }); - it('should return false when head is null instead of a node', () => { - const test3 = null; - expect(hasCycle(test3)).to.equal(false); - }); + it('should return false when head is null instead of a node', () => { + const test3 = null; + expect(hasCycle(test3)).to.equal(false); + }); - it('should return false when the linked list only has one node that points to null', () => { - const test4 = new Node(1); - expect(hasCycle(test4)).to.equal(false); - }); + it('should return false when the linked list only has one node that points to null', () => { + const test4 = new Node(1); + expect(hasCycle(test4)).to.equal(false); + }); - it('should return false when the linked list only has two nodes', () => { - const test5 = new Node(1); - test5.insert(2); - expect(hasCycle(test5)).to.equal(false); - }); + it('should return false when the linked list only has two nodes', () => { + const test5 = new Node(1); + test5.insert(2); + expect(hasCycle(test5)).to.equal(false); + }); - it('should return false when the linked list only has two nodes but the tail links to head', () => { - const test6 = new Node(1); - const tail6 = test6.insert(2); // tail6 === Node #2 - tail6.next = test6; - expect(hasCycle(test6)).to.equal(true); - }); -}); + it('should return false when the linked list only has two nodes but the tail links to head', () => { + const test6 = new Node(1); + const tail6 = test6.insert(2); // tail6 === Node #2 + tail6.next = test6; + expect(hasCycle(test6)).to.equal(true); + }); +}) diff --git a/test/Data Structures/reverse-doubly-linked-list.test.js b/test/Data Structures/reverse-doubly-linked-list.test.js index 7545ba3..4acc443 100644 --- a/test/Data Structures/reverse-doubly-linked-list.test.js +++ b/test/Data Structures/reverse-doubly-linked-list.test.js @@ -1,28 +1,29 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); const { reverse, DoublyLinkedListNode, DoublyLinkedList } = require('../../src/Data Structures/reverse-doubly-linked-list'); +const { describe, it } = require('mocha') +const { expect } = require('chai') + describe('Reverse Doubly Linked List', () => { - it('should reverse an empty list', () => { - const node = new DoublyLinkedListNode(1); - expect(reverse(node)).to.deep.equal(node); - }); + it('should reverse an empty list', () => { + let node = new DoublyLinkedListNode(1) + expect(reverse(node)).to.deep.equal(node) + }) - it('should reverse a chain of linked nodes', () => { - const list = new DoublyLinkedList(); - list.insertNode(1); - list.insertNode(2); - list.insertNode(3); - list.insertNode(4); - list.insertNode(5); + it('should reverse a chain of linked nodes', () => { + let list = new DoublyLinkedList(); + list.insertNode(1) + list.insertNode(2) + list.insertNode(3) + list.insertNode(4) + list.insertNode(5) - const reversedList = new DoublyLinkedList(); - reversedList.insertNode(5); - reversedList.insertNode(4); - reversedList.insertNode(3); - reversedList.insertNode(2); - reversedList.insertNode(1); + let reversedList = new DoublyLinkedList(); + reversedList.insertNode(5) + reversedList.insertNode(4) + reversedList.insertNode(3) + reversedList.insertNode(2) + reversedList.insertNode(1) - expect(reverse(list.head)).to.deep.equal(reversedList.head); - }); -}); + expect(reverse(list.head)).to.deep.equal(reversedList.head) + }) +}) \ No newline at end of file diff --git a/test/Numbers/plus-minus.test.js b/test/Numbers/plus-minus.test.js index 86cc971..7fa3ced 100644 --- a/test/Numbers/plus-minus.test.js +++ b/test/Numbers/plus-minus.test.js @@ -1,17 +1,17 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const plusMinus = require('../../src/Numbers/plus-minus'); +const plusMinus = require('../../src/Numbers/plus-minus') +const { describe, it } = require('mocha') +const { expect } = require('chai') describe('Plus Minus Problem', () => { - it('It should Return 2 Positive 2 Negative and 1 Zero', () => { - expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({ positive: 2, negative: 2, zero: 1 }); - }); + it('It should Return 2 Positive 2 Negative and 1 Zero', () => { + expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({positive: 2, negative: 2, zero: 1 }); + }); - it('It should Return 5 Positive', () => { - expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({ positive: 5, negative: 0, zero: 0 }); - }); + it('It should Return 5 Positive', () => { + expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({positive: 5, negative: 0, zero: 0 }); + }); - it('It should Return 5 Negative', () => { - expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({ positive: 0, negative: 5, zero: 0 }); - }); -}); + it('It should Return 5 Negative', () => { + expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({positive: 0, negative: 5, zero: 0 }); + }); +}) diff --git a/test/Strings/hackerrank-in-string.test.js b/test/Strings/hackerrank-in-string.test.js index fdbd886..349627c 100644 --- a/test/Strings/hackerrank-in-string.test.js +++ b/test/Strings/hackerrank-in-string.test.js @@ -1,24 +1,28 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const hackerrankInString = require('../../src/Strings/hackerrank-in-string'); +const hackerrankInString = require("../../src/Strings/hackerrank-in-string"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('HackerRank in a String', () => { - it('should return NO for any empty string', () => { - expect(hackerrankInString('')).to.equal('NO'); - }); +describe("HackerRank in a String", () => { + it("should return NO for any empty string", () => { + expect(hackerrankInString("")).to.equal("NO"); + }); - it('should return YES for an exact match', () => { - expect(hackerrankInString('hackerrank')).to.equal('YES'); - }); + it("should return YES for an exact match", () => { + expect(hackerrankInString("hackerrank")).to.equal("YES"); + }); - describe('should return YES inputs containing hackerrank', () => { - it('hereiamstackerrank', () => expect(hackerrankInString('hereiamstackerrank')).to.equal('YES')); - it('hhaacckkekraraannk', () => expect(hackerrankInString('hhaacckkekraraannk')).to.equal('YES')); - }); - describe("should return NO for inputs that don't contain hackerrank", () => { - it('hackerworld', () => expect(hackerrankInString('hackerworld')).to.equal('NO')); - it('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt', () => expect( - hackerrankInString('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt'), - ).to.equal('NO')); - }); + describe("should return YES inputs containing hackerrank", () => { + it("hereiamstackerrank", () => + expect(hackerrankInString("hereiamstackerrank")).to.equal("YES")); + it("hhaacckkekraraannk", () => + expect(hackerrankInString("hhaacckkekraraannk")).to.equal("YES")); + }); + describe("should return NO for inputs that don't contain hackerrank", () => { + it("hackerworld", () => + expect(hackerrankInString("hackerworld")).to.equal("NO")); + it("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt", () => + expect( + hackerrankInString("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt") + ).to.equal("NO")); + }); }); diff --git a/test/Strings/repeated-string.test.js b/test/Strings/repeated-string.test.js index 0dd8a47..7003391 100644 --- a/test/Strings/repeated-string.test.js +++ b/test/Strings/repeated-string.test.js @@ -1,25 +1,25 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const repeatedString = require('../../src/Strings/repeated-string'); +const repeatedString = require("../../src/Strings/repeated-string"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Repeated String', () => { - it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { - expect(repeatedString('aba', 10)).to.eq(7); - }); +describe("Repeated String", () => { + it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { + expect(repeatedString("aba", 10)).to.eq(7); + }); - it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { - expect(repeatedString('aaaaaa', 1)).to.eq(1); - }); + it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { + expect(repeatedString("aaaaaa", 1)).to.eq(1); + }); - it("should return n if input string is 'a'", () => { - expect(repeatedString('a', 100000)).to.eq(100000); - expect(repeatedString('a', 300)).to.eq(300); - expect(repeatedString('a', 5)).to.eq(5); - }); + it("should return n if input string is 'a'", () => { + expect(repeatedString("a", 100000)).to.eq(100000); + expect(repeatedString("a", 300)).to.eq(300); + expect(repeatedString("a", 5)).to.eq(5); + }); - it("should return 0 if the input string does not contain 'a'", () => { - expect(repeatedString('test', 20)).to.eq(0); - expect(repeatedString('bbbb', 7)).to.eq(0); - expect(repeatedString('cdcdcd', 5)).to.eq(0); - }); + it("should return 0 if the input string does not contain 'a'", () => { + expect(repeatedString("test", 20)).to.eq(0); + expect(repeatedString("bbbb", 7)).to.eq(0); + expect(repeatedString("cdcdcd", 5)).to.eq(0); + }); }); diff --git a/test/Strings/strong-password.test.js b/test/Strings/strong-password.test.js index 4e70cfc..f9fec61 100644 --- a/test/Strings/strong-password.test.js +++ b/test/Strings/strong-password.test.js @@ -1,19 +1,26 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const passwordStrengthMinimumNumber = require('../../src/Strings/strong-password'); +const passwordStrengthMinimumNumber = require("../../src/Strings/strong-password"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Strong Password', () => { - it('returns 6 for empty string', () => expect(passwordStrengthMinimumNumber(0, '')).to.equal(6)); +describe("Strong Password", () => { + it("returns 6 for empty string", () => + expect(passwordStrengthMinimumNumber(0, "")).to.equal(6)); - it('returns 3 with password length of 3', () => expect(passwordStrengthMinimumNumber(3, 'Ab1')).to.equal(3)); + it("returns 3 with password length of 3", () => + expect(passwordStrengthMinimumNumber(3, "Ab1")).to.equal(3)); - it('returns 3 with missing special character, number and uppercase letter', () => expect(passwordStrengthMinimumNumber(3, 'longenough')).to.equal(3)); + it("returns 3 with missing special character, number and uppercase letter", () => + expect(passwordStrengthMinimumNumber(3, "longenough")).to.equal(3)); - it('returns 1 with missing number', () => expect(passwordStrengthMinimumNumber(11, '#HackerRank')).to.equal(1)); + it("returns 1 with missing number", () => + expect(passwordStrengthMinimumNumber(11, "#HackerRank")).to.equal(1)); - it('returns 1 with missing special character', () => expect(passwordStrengthMinimumNumber(11, '1HackerRank')).to.equal(1)); + it("returns 1 with missing special character", () => + expect(passwordStrengthMinimumNumber(11, "1HackerRank")).to.equal(1)); - it('returns 1 with missing uppercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1hackerrank')).to.equal(1)); + it("returns 1 with missing uppercase letter", () => + expect(passwordStrengthMinimumNumber(12, "#1hackerrank")).to.equal(1)); - it('returns 1 with missing lowercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1HACKERRANK')).to.equal(1)); + it("returns 1 with missing lowercase letter", () => + expect(passwordStrengthMinimumNumber(12, "#1HACKERRANK")).to.equal(1)); }); diff --git a/test/Strings/time-conversion.test.js b/test/Strings/time-conversion.test.js index 5e940bc..16ba822 100644 --- a/test/Strings/time-conversion.test.js +++ b/test/Strings/time-conversion.test.js @@ -1,21 +1,21 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const timeConversion = require('../../src/Strings/time-conversion'); +const timeConversion = require("../../src/Strings/time-conversion"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Time Conversion', () => { - it('should convert midnight', () => { - expect(timeConversion('12:00:00AM')).to.eq('00:00:00'); - }); +describe("Time Conversion", () => { + it("should convert midnight", () => { + expect(timeConversion("12:00:00AM")).to.eq("00:00:00") + }); - it('should convert noon', () => { - expect(timeConversion('12:00:00PM')).to.eq('12:00:00'); - }); + it("should convert noon", () => { + expect(timeConversion("12:00:00PM")).to.eq("12:00:00") + }); - it('should convert an AM time', () => { - expect(timeConversion('07:05:45AM')).to.eq('07:05:45'); - }); + it("should convert an AM time", () => { + expect(timeConversion("07:05:45AM")).to.eq("07:05:45") + }); - it('should convert a PM time', () => { - expect(timeConversion('07:05:45PM')).to.eq('19:05:45'); - }); -}); + it("should convert a PM time", () => { + expect(timeConversion("07:05:45PM")).to.eq("19:05:45") + }); +}); \ No newline at end of file From d9e5dfc509068d2dff7a1a21aebf1c047fb05cb0 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Fri, 29 Oct 2021 00:02:02 +0530 Subject: [PATCH 7/8] Fix Build errors --- src/Arrays/2d-array-ds.js | 22 ++--- src/Arrays/apple-and-orange.js | 27 +++--- src/Arrays/array-manipulation.js | 18 ++-- src/Arrays/birthday-cake-candles.js | 24 ++--- src/Arrays/breaking-best-and-worst-records.js | 62 +++++++------ src/Arrays/compare-the-triplets.js | 20 ++--- src/Arrays/diagonal-difference.js | 21 +++-- src/Arrays/jumping-on-the-clouds.js | 31 ++++--- src/Arrays/left-rotation.js | 17 ++-- src/Arrays/minimum-swaps-2.js | 35 ++++---- src/Arrays/newyear-chaos.js | 36 ++++---- src/Arrays/sock-merchant.js | 36 ++++---- src/Data Structures/cycle-detection.js | 39 ++++---- .../reverse-doubly-linked-list.js | 85 +++++++++--------- .../count-triplet.js | 37 ++++---- .../custom-hashmap.js | 40 ++++----- .../frequency-queries.js | 58 ++++++------ .../game-of-thrones.js | 14 +-- src/Dictionaries and Hashmaps/ransom-note.js | 71 +++++++-------- .../sherlock-and-anagrams.js | 32 +++---- src/Dictionaries and Hashmaps/two-strings.js | 25 +++--- src/Numbers/grading.js | 27 +++--- src/Numbers/kangaroo.js | 44 +++++---- src/Numbers/plus-minus.js | 34 +++---- src/Numbers/staircase.js | 8 +- src/Sorting/bubble-sort.js | 30 +++---- src/Sorting/mark-and-toys.js | 28 +++--- src/Sorting/mini-max-sum.js | 14 +-- src/Strings/alternating-characters.js | 26 +++--- src/Strings/counting-valleys.js | 34 ++++--- src/Strings/hackerrank-in-string.js | 16 ++-- src/Strings/making-anagrams.js | 72 ++++++++------- src/Strings/repeated-string.js | 16 ++-- src/Strings/sherlock-and-the-valid-string.js | 61 +++++++------ src/Strings/strong-password.js | 32 +++---- src/Strings/time-conversion.js | 31 ++++--- test/Arrays/birthday-cake-candles.test.js | 46 +++++----- test/Arrays/left-rotation.test.js | 34 ++++--- test/Data Structures/cycle-detection.test.js | 90 +++++++++---------- .../reverse-doubly-linked-list.test.js | 45 +++++----- test/Numbers/plus-minus.test.js | 26 +++--- test/Strings/hackerrank-in-string.test.js | 44 +++++---- test/Strings/repeated-string.test.js | 40 ++++----- test/Strings/strong-password.test.js | 29 +++--- test/Strings/time-conversion.test.js | 34 +++---- 45 files changed, 782 insertions(+), 829 deletions(-) diff --git a/src/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js index 1e5a28e..6bb6e73 100644 --- a/src/Arrays/2d-array-ds.js +++ b/src/Arrays/2d-array-ds.js @@ -4,14 +4,14 @@ Score: 15 Link: https://www.hackerrank.com/challenges/2d-array/ */ -function hourglassSum(arr) { - var sum = -1000 - let max = sum - for(let i = 0 ; i<4;i++){ - for(let j = 0 ; j<4; j++){ - sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] - if(sum>max) max = sum - } - } - console.log(max) -} +module.exports = function hourglassSum(arr) { + let sum = -1000; + let max = sum; + for (let i = 0; i < 4; i++) { + for (let j = 0; j < 4; j++) { + sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; + if (sum > max) max = sum; + } + } + console.log(max); +}; diff --git a/src/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js index ffaf16a..6574de8 100644 --- a/src/Arrays/apple-and-orange.js +++ b/src/Arrays/apple-and-orange.js @@ -5,22 +5,21 @@ Link: https://www.hackerrank.com/challenges/apple-and-orange */ -function countApplesAndOranges(s, t, a, b, apples, oranges) { - countFruitsFallInsideHome(apples, s - a, t - a); - countFruitsFallInsideHome(oranges, s - b, t - b); -} - - function countFruitsFallInsideHome(fruits, startHome, EndHome) { - let counter = 0; - fruits.forEach(fruit => { - if (fruit >= startHome && fruit <= EndHome) { - return counter++; - } - }); + let counter = 0; + fruits.forEach((fruit) => { + if (fruit >= startHome && fruit <= EndHome) { + counter++; + } + return counter; + }); - return console.log(counter); + return console.log(counter); } -countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1] , [5 -6]); +function countApplesAndOranges(s, t, a, b, apples, oranges) { + countFruitsFallInsideHome(apples, s - a, t - a); + countFruitsFallInsideHome(oranges, s - b, t - b); +} +countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1], [5 - 6]); diff --git a/src/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js index 45eaf1d..a04ae2b 100644 --- a/src/Arrays/array-manipulation.js +++ b/src/Arrays/array-manipulation.js @@ -5,14 +5,14 @@ Link: https://www.hackerrank.com/challenges/crush/problem */ -function arrayManipulation(n, queries) { - let arr = Array(n).fill(0); +module.exports = function arrayManipulation(n, queries) { + const arr = Array(n).fill(0); - for (let a = 0; a < queries.length; a++) { - for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { - arr[index] += queries[a][2]; - } - } + for (let a = 0; a < queries.length; a++) { + for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { + arr[index] += queries[a][2]; + } + } - return Math.max(...arr); -} + return Math.max(...arr); +}; diff --git a/src/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js index 35ed0d7..674311e 100644 --- a/src/Arrays/birthday-cake-candles.js +++ b/src/Arrays/birthday-cake-candles.js @@ -6,16 +6,16 @@ */ module.exports = function birthdayCakeCandles(arr) { - let tallestCandle = 0; - let candlesCounter = 0; - for (let index = 0; index < arr.length; index++) { - if (arr[index] > tallestCandle) { - tallestCandle = arr[index]; - candlesCounter = 1; - } else if (arr[index] === tallestCandle) { - candlesCounter++; - } - } + let tallestCandle = 0; + let candlesCounter = 0; + for (let index = 0; index < arr.length; index++) { + if (arr[index] > tallestCandle) { + tallestCandle = arr[index]; + candlesCounter = 1; + } else if (arr[index] === tallestCandle) { + candlesCounter++; + } + } - return candlesCounter; -} + return candlesCounter; +}; diff --git a/src/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js index 1afad77..9df7f33 100644 --- a/src/Arrays/breaking-best-and-worst-records.js +++ b/src/Arrays/breaking-best-and-worst-records.js @@ -6,37 +6,35 @@ */ function breakingRecords(scores) { - - let counters = { - min: 0, - max: 0 - }; - - let values = { - min: 0, - max: 0 - } - let isDefaultSet = false; - - scores.forEach(score => { - if (!isDefaultSet) { - values.min = score; - values.max = score; - isDefaultSet = true; - return ; - } - - if (score > values.max) { - values.max = score; - counters.max++; - } else if (score < values.min) { - values.min = score; - counters.min++; - } - }) - - return [counters.max, counters.min]; - + const counters = { + min: 0, + max: 0, + }; + + const values = { + min: 0, + max: 0, + }; + let isDefaultSet = false; + + scores.forEach((score) => { + if (!isDefaultSet) { + values.min = score; + values.max = score; + isDefaultSet = true; + return; + } + + if (score > values.max) { + values.max = score; + counters.max++; + } else if (score < values.min) { + values.min = score; + counters.min++; + } + }); + + return [counters.max, counters.min]; } -breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]) +breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]); diff --git a/src/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js index 75d6007..b542423 100644 --- a/src/Arrays/compare-the-triplets.js +++ b/src/Arrays/compare-the-triplets.js @@ -6,16 +6,16 @@ Link: https://www.hackerrank.com/challenges/compare-the-triplets/problem */ function compareTriplets(a, b) { - let points = [0, 0]; - for (let index = 0; index < a.length; index++){ - if (a[index] > b[index]) { - points[0] += 1; - } else if (a[index] < b[index]) { - points[1] += 1; - } - } + const points = [0, 0]; + for (let index = 0; index < a.length; index++) { + if (a[index] > b[index]) { + points[0] += 1; + } else if (a[index] < b[index]) { + points[1] += 1; + } + } - return points; + return points; } -console.log(compareTriplets([5, 6, 7], [3, 6, 10])) +console.log(compareTriplets([5, 6, 7], [3, 6, 10])); diff --git a/src/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js index 336b05d..5304e9e 100644 --- a/src/Arrays/diagonal-difference.js +++ b/src/Arrays/diagonal-difference.js @@ -1,4 +1,3 @@ - /* Title:Diagonal Difference Difficulty: Easy @@ -7,16 +6,16 @@ */ function diagonalDifference(arr) { - let leftToRight = 0; - let rightToLeft = 0; - let tmpLength = arr.length; - for (let i = 0; i < arr.length; i++){ - leftToRight += arr[i][i]; - rightToLeft += arr[i][--tmpLength]; - } + let leftToRight = 0; + let rightToLeft = 0; + let tmpLength = arr.length; + for (let i = 0; i < arr.length; i++) { + leftToRight += arr[i][i]; + rightToLeft += arr[i][--tmpLength]; + } - return Math.abs(leftToRight - rightToLeft); + return Math.abs(leftToRight - rightToLeft); } -let input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] -console.log(diagonalDifference(input)) +const input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]; +console.log(diagonalDifference(input)); diff --git a/src/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js index 9f5c7d1..5a4095a 100644 --- a/src/Arrays/jumping-on-the-clouds.js +++ b/src/Arrays/jumping-on-the-clouds.js @@ -5,20 +5,19 @@ Link: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ */ -function jumpingOnClouds(c) { +module.exports = function jumpingOnClouds(c) { + let jump = 0; + for (let i = 0; i < c.length;) { + if (c[i + 2] === '0') { + jump++; + i += 2; + } else if (c[i + 1] === '0') { + jump++; + i += 1; + } else { + i++; + } + } - let jump = 0; - for (let i = 0; i < c.length;){ - if (c[i + 2] == 0) { - jump++; - i += 2; - } else if (c[i + 1] == 0) { - jump++; - i += 1; - } else { - i++; - } - } - - return jump; -} + return jump; +}; diff --git a/src/Arrays/left-rotation.js b/src/Arrays/left-rotation.js index 17ed7de..7881ba7 100644 --- a/src/Arrays/left-rotation.js +++ b/src/Arrays/left-rotation.js @@ -6,14 +6,13 @@ */ module.exports = function rotLeft(a, d) { + if (!a.length) { + return []; + } - if(!a.length){ - return [] - } + for (let i = 0; i < d; i++) { + a.push(a.shift()); + } - for (let i = 0; i < d; i++) { - a.push(a.shift()); - } - - return a; -} + return a; +}; diff --git a/src/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js index c382556..95c93fc 100644 --- a/src/Arrays/minimum-swaps-2.js +++ b/src/Arrays/minimum-swaps-2.js @@ -5,22 +5,21 @@ Link: https://www.hackerrank.com/challenges/minimum-swaps-2 */ +module.exports = function minimumSwaps(arr) { + const origArray = arr.slice(0); + const sortedArray = arr.sort((a, b) => a - b); + let numberOfSwap = 0; + for (let i = 0; i < origArray.length; i++) { + if (origArray[i] !== sortedArray[i]) { + for (let j = i + 1; j < origArray.length; j++) { + if (origArray[j] === sortedArray[i]) { + [origArray[i], origArray[j]] = [origArray[j], origArray[i]]; + numberOfSwap++; + break; + } + } + } + } -function minimumSwaps(arr) { - var origArray = arr.slice(0); - var sortedArray = arr.sort((a,b) => a-b); - let numberOfSwap = 0; - for (var i = 0; i < origArray.length; i++) { - if (origArray[i] != sortedArray[i]) { - for (var j = i + 1; j < origArray.length; j++) { - if (origArray[j] === sortedArray[i]) { - [origArray[i], origArray[j]] = [origArray[j], origArray[i]] - numberOfSwap++ - break; - } - } - } - } - - return numberOfSwap; -} + return numberOfSwap; +}; diff --git a/src/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js index 0ae6270..08eb21a 100644 --- a/src/Arrays/newyear-chaos.js +++ b/src/Arrays/newyear-chaos.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/new-year-chaos/ */ -function minimumBribes(q) { - let swaps = 0; - let min = q.length; - for (var i = q.length -1 ; i >= 0; i--) { - if (q[i] - i > 3) { - return `Too chaotic`; - } - if (q[i] > i + 1) { - swaps += (q[i] - (i + 1)); - } else { - if (min > q[i]) { - min = q[i]; - } else if (q[i] != min) { - swaps++; - } - } - } +module.exports = function minimumBribes(q) { + let swaps = 0; + let min = q.length; + for (let i = q.length - 1; i >= 0; i--) { + if (q[i] - i > 3) { + return 'Too chaotic'; + } + if (q[i] > i + 1) { + swaps += (q[i] - (i + 1)); + } else if (min > q[i]) { + min = q[i]; + } else if (q[i] !== min) { + swaps++; + } + } - return swaps; -} + return swaps; +}; diff --git a/src/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js index e865834..c75cf50 100644 --- a/src/Arrays/sock-merchant.js +++ b/src/Arrays/sock-merchant.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/sock-merchant */ +module.exports = function sockMerchant(n, ar) { + const tmpArr = []; + let counter = 0; + ar.map((value) => { + if (tmpArr.includes(value)) { + const index = tmpArr.indexOf(value); + if (index > -1) { + tmpArr.splice(index, 1); + } + counter++; + } else { + tmpArr.push(value); + } + return value; + }); -function sockMerchant(n, ar) { - let tmpArr = []; - let counter = 0; - ar.map(value => { - if (tmpArr.includes(value)) { - var index = tmpArr.indexOf(value); - if (index > -1) { - tmpArr.splice(index, 1); - } - counter++; - } else { - tmpArr.push(value); - } - - }) - - return counter; - -} + return counter; +}; diff --git a/src/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js index 5bd280a..46ee960 100644 --- a/src/Data Structures/cycle-detection.js +++ b/src/Data Structures/cycle-detection.js @@ -6,30 +6,31 @@ */ function hasCycle(head) { - if (head === null || head.next === null || head.next.next === null) return false; // edge cases - let hare = head; - let tortoise = head; - do { - hare = hare.next.next; // 'hare' moves twice per tick - tortoise = tortoise.next; // 'tortoise' moves once per tick - } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); - return hare === tortoise; + if (head === null || head.next === null || head.next.next === null) return false; // edge cases + let hare = head; + let tortoise = head; + do { + hare = hare.next.next; // 'hare' moves twice per tick + tortoise = tortoise.next; // 'tortoise' moves once per tick + } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); + return hare === tortoise; } // NODE CLASS class Node { - constructor (data) { - this.data = data; - this.next = null; - } - insert (data) { - this.next = new Node(data); - return this.next; // for chaining - } + constructor(data) { + this.data = data; + this.next = null; + } + + insert(data) { + this.next = new Node(data); + return this.next; // for chaining + } } module.exports = { - hasCycle, - Node, -}; \ No newline at end of file + hasCycle, + Node, +}; diff --git a/src/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js index 04dcde3..c5bae4f 100644 --- a/src/Data Structures/reverse-doubly-linked-list.js +++ b/src/Data Structures/reverse-doubly-linked-list.js @@ -1,4 +1,3 @@ -'use strict'; /* Title: Reverse a doubly linked list Difficulty: Easy @@ -6,51 +5,49 @@ Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem */ - -function reverse(head) { - while (head.next) { - head = head.next - } - - const newList = new DoublyLinkedList(); - - while (head) { - newList.insertNode(head.data); - head = head.prev - } - return newList.head -} - class DoublyLinkedListNode { - constructor(nodeData) { - this.data = nodeData; - this.next = null; - this.prev = null; - } -}; + constructor(nodeData) { + this.data = nodeData; + this.next = null; + this.prev = null; + } +} class DoublyLinkedList { - constructor() { - this.head = null; - this.tail = null; - } - - insertNode(nodeData) { - let node = new DoublyLinkedListNode(nodeData); - - if (this.head == null) { - this.head = node; - } else { - this.tail.next = node; - node.prev = this.tail; - } - - this.tail = node; - } -}; + constructor() { + this.head = null; + this.tail = null; + } + + insertNode(nodeData) { + const node = new DoublyLinkedListNode(nodeData); + + if (this.head == null) { + this.head = node; + } else { + this.tail.next = node; + node.prev = this.tail; + } + + this.tail = node; + } +} +function reverse(head) { + while (head.next) { + head = head.next; + } -module.exports = { - reverse, - DoublyLinkedList, - DoublyLinkedListNode + const newList = new DoublyLinkedList(); + + while (head) { + newList.insertNode(head.data); + head = head.prev; + } + return newList.head; } + +module.exports = { + reverse, + DoublyLinkedList, + DoublyLinkedListNode, +}; diff --git a/src/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js index ac8d48c..38656ad 100644 --- a/src/Dictionaries and Hashmaps/count-triplet.js +++ b/src/Dictionaries and Hashmaps/count-triplet.js @@ -6,30 +6,29 @@ */ function countTriplets(arr, r) { - let second = {} - let third = {} - let count = 0; - for (let index = 0; index < arr.length; index++) { + const second = {}; + const third = {}; + let count = 0; + for (let index = 0; index < arr.length; index++) { + const val = arr[index]; - const val = arr[index]; + // If value found on third then add it to count + if (third[val]) { + count += third[val]; + } - //If value found on third then add it to count - if(third[val]){ - count += third[val]; - } + // If value found on second , convey it to third - //If value found on second , convey it to third + if (second[val]) { + third[val * r] = third[val * r] + second[val] || second[val]; + } - if(second[val]){ - third[val*r] = third[val*r] + second[val] || second[val]; - } + // add current element into second value - //add current element into second value + second[val * r] = second[val * r] + 1 || 1; + } - second[val*r] = second[val*r]+1 || 1; - } - - return count; + return count; } -console.log(countTriplets([1,2 ,2,4], 2)); +console.log(countTriplets([1, 2, 2, 4], 2)); diff --git a/src/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js index c2431ec..4c05db3 100644 --- a/src/Dictionaries and Hashmaps/custom-hashmap.js +++ b/src/Dictionaries and Hashmaps/custom-hashmap.js @@ -5,31 +5,31 @@ Link: - */ class customHashMap { - constructor() { - this.list = []; - } + constructor() { + this.list = []; + } - get(x) { - return this.list[this.hashCode(x)]; - } + get(x) { + return this.list[this.hashCode(x)]; + } - set(x, y) { - this.list[this.hashCode(x)] = y; - } + set(x, y) { + this.list[this.hashCode(x)] = y; + } - hashCode(str) { - let hash = 0; - if (str.length == 0) return hash; - for (let i = 0; i < str.length; i++) { - let char = str.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash = hash & hash; // Convert to 32bit integer - } - return hash; - } + static hashCode(str) { + let hash = 0; + if (str.length === 0) return hash; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash &= hash; // Convert to 32bit integer + } + return hash; + } } -let m = new customHashMap(); +const m = customHashMap(); m.set('hello', 'world'); console.log(m.get('hello')); diff --git a/src/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js index c3f4d5a..40ccb6b 100644 --- a/src/Dictionaries and Hashmaps/frequency-queries.js +++ b/src/Dictionaries and Hashmaps/frequency-queries.js @@ -6,40 +6,40 @@ */ function freqQuery(arr) { - const result = []; - const hash = {}; - const freq = []; + const result = []; + const hash = {}; + const freq = []; - for (let i = 0; i < arr.length; i += 1) { - const [action, value] = arr[i]; - const initValue = hash[value] || 0; + for (let i = 0; i < arr.length; i += 1) { + const [action, value] = arr[i]; + const initValue = hash[value] || 0; - if (action === 1) { - hash[value] = initValue + 1; - freq[initValue] = (freq[initValue] || 0) - 1; - freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; - } + if (action === 1) { + hash[value] = initValue + 1; + freq[initValue] = (freq[initValue] || 0) - 1; + freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; + } - if (action === 2 && initValue > 0) { - hash[value] = initValue - 1; - freq[initValue - 1] += 1; - freq[initValue] -= 1; - } + if (action === 2 && initValue > 0) { + hash[value] = initValue - 1; + freq[initValue - 1] += 1; + freq[initValue] -= 1; + } - if (action === 3) result.push(freq[value] > 0 ? 1 : 0); - } + if (action === 3) result.push(freq[value] > 0 ? 1 : 0); + } - return result; + return result; } -let input = [ - [1, 5], - [1, 6], - [3, 2], - [1, 10], - [1, 10], - [1, 6], - [2, 5], - [3, 2] - ]; +const input = [ + [1, 5], + [1, 6], + [3, 2], + [1, 10], + [1, 10], + [1, 6], + [2, 5], + [3, 2], +]; console.log(freqQuery(input)); diff --git a/src/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js index 0d50f1e..31e1f31 100644 --- a/src/Dictionaries and Hashmaps/game-of-thrones.js +++ b/src/Dictionaries and Hashmaps/game-of-thrones.js @@ -6,12 +6,12 @@ */ function gameOfThrones(s) { - const frequencies = {}; - for (let char of s) frequencies[char] = frequencies[char] + 1 || 1; - let oddFrequencies = Object.values(frequencies).filter(frequency => frequency % 2); - return oddFrequencies.length <= 1 ? 'YES' : 'NO'; + const frequencies = {}; + for (const char of s) frequencies[char] = frequencies[char] + 1 || 1; + const oddFrequencies = Object.values(frequencies).filter((frequency) => frequency % 2); + return oddFrequencies.length <= 1 ? 'YES' : 'NO'; } -console.log(gameOfThrones('aaabbbb')); // YES -console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO -console.log(gameOfThrones('cdcdcdcdeeeef')); // YES \ No newline at end of file +console.log(gameOfThrones('aaabbbb')); // YES +console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO +console.log(gameOfThrones('cdcdcdcdeeeef')); // YES diff --git a/src/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js index bf7003a..2268c69 100644 --- a/src/Dictionaries and Hashmaps/ransom-note.js +++ b/src/Dictionaries and Hashmaps/ransom-note.js @@ -6,51 +6,48 @@ */ class ExtendedMap { - - constructor(){ - this.map = new Map(); - } - - get(x) { - let value = this.map.get(x); - if (value === 1) { - this.map.delete(x); - return true; - } - - return this.map.set(x, --value); - } - - set(x, y) { - if (this.map.get(x)) { - return this.map.set(x, this.map.get(x) + 1); - } - - return this.map.set(x, y); - } + constructor() { + this.map = new Map(); + } + + get(x) { + let value = this.map.get(x); + if (value === 1) { + this.map.delete(x); + return true; + } + + return this.map.set(x, --value); + } + + set(x, y) { + if (this.map.get(x)) { + return this.map.set(x, this.map.get(x) + 1); + } + + return this.map.set(x, y); + } } - function checkMagazine(magazine, note) { + const m = new ExtendedMap(); - let m = new ExtendedMap() - - for (let i = 0; i < magazine.length; i++) { - m.set(magazine[i], 1) - } + for (let i = 0; i < magazine.length; i++) { + m.set(magazine[i], 1); + } - for (let i = 0; i < note.length; i++) { - if (!m.get(note[i])) { - console.log('No'); - return; - }; - } + for (let i = 0; i < note.length; i++) { + if (!m.get(note[i])) { + console.log('No'); + return; + } + } - console.log('Yes'); + console.log('Yes'); } -let magazine = [ 'give', 'me', 'one', 'grand', 'today', 'night' ]; -let note = [ 'give', 'one', 'grand', 'today' ]; +const magazine = ['give', 'me', 'one', 'grand', 'today', 'night']; +const note = ['give', 'one', 'grand', 'today']; console.time('Time Taken'); checkMagazine(magazine, note); diff --git a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js index 138f0db..8b655d9 100644 --- a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js +++ b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js @@ -5,23 +5,23 @@ Link: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ */ function sherlockAndAnagrams(s) { - let count = 0; - let strLength = s.length; //get length - for (let i = 1; i < strLength; i++) { - let found = {}; - for (let j = 0; j + i <= strLength; j++) { - let substr = s.substr(j, i); //device string into substr - substr = substr.split('').sort().join(''); //sort it - if (found[substr]) { - count += found[substr]; //count total - found[substr]++; - } else { - found[substr] = 1; - } - } - } + let count = 0; + const strLength = s.length; // get length + for (let i = 1; i < strLength; i++) { + const found = {}; + for (let j = 0; j + i <= strLength; j++) { + let substr = s.substr(j, i); // device string into substr + substr = substr.split('').sort().join(''); // sort it + if (found[substr]) { + count += found[substr]; // count total + found[substr]++; + } else { + found[substr] = 1; + } + } + } - return count; + return count; } console.log(sherlockAndAnagrams('cdcd')); diff --git a/src/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js index f9f7e3d..cc1845d 100644 --- a/src/Dictionaries and Hashmaps/two-strings.js +++ b/src/Dictionaries and Hashmaps/two-strings.js @@ -6,22 +6,21 @@ */ function twoStrings(s1, s2) { - m = new Map(); - for(let i=0; i { - if (grade < 38) { - return grade; - } +module.exports = function gradingStudents(grades) { + const newGrades = grades.map((grade) => { + if (grade < 38) { + return grade; + } - let roundRemainder = grade % 5; + const roundRemainder = grade % 5; - if (roundRemainder === 0 || roundRemainder <= 2) { - return grade; - } + if (roundRemainder === 0 || roundRemainder <= 2) { + return grade; + } - return grade + (5 - roundRemainder); - }) + return grade + (5 - roundRemainder); + }); - return newGrades; - -} + return newGrades; +}; diff --git a/src/Numbers/kangaroo.js b/src/Numbers/kangaroo.js index 06495a1..90ae9da 100644 --- a/src/Numbers/kangaroo.js +++ b/src/Numbers/kangaroo.js @@ -7,29 +7,26 @@ // Solution 1 function kangaroo(x1, v1, x2, v2) { - if ((x2 > x1 && v2 > v1) || v1 === v2) { - return 'NO'; - } + if ((x2 > x1 && v2 > v1) || v1 === v2) { + return 'NO'; + } - let x1Distance = x1; - let x2Distance = x2; + let x1Distance = x1; + let x2Distance = x2; - while (x1Distance !== x2Distance) { - x1Distance += v1; - x2Distance += v2; + while (x1Distance !== x2Distance) { + x1Distance += v1; + x2Distance += v2; - if (x1Distance > x2Distance) { - return 'NO'; - } - } - - return 'YES'; + if (x1Distance > x2Distance) { + return 'NO'; + } + } + return 'YES'; } - -//Solution 2 - +// Solution 2 /* @@ -46,11 +43,12 @@ x1 - x2 / v2 - v1 = y so we can find y with all 4 inputs if it is integer and greater than 0 then both will meet */ -function kangaroo(x1, v1, x2, v2) { - if (x2 > x1 && v2 > v1) { - return 'NO' - } +function kangarooSolution2(x1, v1, x2, v2) { + if (x2 > x1 && v2 > v1) { + return 'NO'; + } - let steps = (x1 - x2) % (v2 - v1); - return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; + const steps = (x1 - x2) % (v2 - v1); + return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; } +module.exports = [kangaroo, kangarooSolution2]; diff --git a/src/Numbers/plus-minus.js b/src/Numbers/plus-minus.js index b754238..164be6c 100644 --- a/src/Numbers/plus-minus.js +++ b/src/Numbers/plus-minus.js @@ -6,22 +6,22 @@ */ module.exports = function plusMinus(arr) { - let result = { - positive: 0, - negative: 0, - zero: 0, - } + const result = { + positive: 0, + negative: 0, + zero: 0, + }; - let arrLength = arr.length; - for (let index = 0; index < arrLength; index++){ - if (arr[index] === 0) { - ++result.zero; - } else if (arr[index] > 0) { - ++result.positive; - } else { - ++result.negative; - } - } + const arrLength = arr.length; + for (let index = 0; index < arrLength; index++) { + if (arr[index] === 0) { + ++result.zero; + } else if (arr[index] > 0) { + ++result.positive; + } else { + ++result.negative; + } + } - return result; -} + return result; +}; diff --git a/src/Numbers/staircase.js b/src/Numbers/staircase.js index f09ff35..6a05c07 100644 --- a/src/Numbers/staircase.js +++ b/src/Numbers/staircase.js @@ -6,10 +6,10 @@ */ function staircase(n) { - let tmp = n; - for (let index = 0; index < n; index++){ - console.log(' '.repeat(--tmp) + '#'.repeat(index + 1 )); - } + let tmp = n; + for (let index = 0; index < n; index++) { + console.log(' '.repeat(--tmp) + '#'.repeat(index + 1)); + } } staircase(6); diff --git a/src/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js index d6d9c81..794c249 100644 --- a/src/Sorting/bubble-sort.js +++ b/src/Sorting/bubble-sort.js @@ -6,22 +6,22 @@ */ function countSwaps(a) { - let isSorted = false; - let counter = 0; - while (!isSorted) { - isSorted = true; - for (let i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - [a[i], a[i + 1]] = [a[i + 1], a[i]]; - counter++; - isSorted = false; - } - } - } + let isSorted = false; + let counter = 0; + while (!isSorted) { + isSorted = true; + for (let i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + [a[i], a[i + 1]] = [a[i + 1], a[i]]; + counter++; + isSorted = false; + } + } + } - console.log(`Array is sorted in ${counter} swaps.`); - console.log(`First Element: ${a[0]}`); - console.log(`Last Element: ${a[a.length -1 ]}`); + console.log(`Array is sorted in ${counter} swaps.`); + console.log(`First Element: ${a[0]}`); + console.log(`Last Element: ${a[a.length - 1]}`); } countSwaps([5, 2, 1]); diff --git a/src/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js index cabb6db..efb5755 100644 --- a/src/Sorting/mark-and-toys.js +++ b/src/Sorting/mark-and-toys.js @@ -6,20 +6,20 @@ */ function maximumToys(prices, balance) { - prices = prices.sort((a, b) => a - b) - let toysBought = 0; - console.log(prices); - for (let i = 0; i < prices.length; i++){ - if (balance >= prices[i]) { - toysBought++; - balance -= prices[i]; - } else { - break; - } - } - return toysBought; - + prices = prices.sort((a, b) => a - b); + let toysBought = 0; + console.log(prices); + for (let i = 0; i < prices.length; i++) { + if (balance >= prices[i]) { + toysBought++; + balance -= prices[i]; + } else { + break; + } + } + return toysBought; } -let arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; +const arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, + 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; console.log(maximumToys(arr, 100000)); diff --git a/src/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js index 83bde36..79d6224 100644 --- a/src/Sorting/mini-max-sum.js +++ b/src/Sorting/mini-max-sum.js @@ -6,14 +6,14 @@ */ function miniMaxSum(arr) { - let sum = [0, 0]; - arr = arr.sort((a, b) => { return a - b }); - for (let i = 0; i < 4; i++){ - sum[0] += arr[i]; - sum[1] += arr[arr.length - (i+1)]; - } + const sum = [0, 0]; + arr = arr.sort((a, b) => a - b); + for (let i = 0; i < 4; i++) { + sum[0] += arr[i]; + sum[1] += arr[arr.length - (i + 1)]; + } - console.log(sum[0], sum[1]); + console.log(sum[0], sum[1]); } miniMaxSum(1, 2, 3, 4, 5); diff --git a/src/Strings/alternating-characters.js b/src/Strings/alternating-characters.js index b02de77..3fbcb1a 100644 --- a/src/Strings/alternating-characters.js +++ b/src/Strings/alternating-characters.js @@ -6,22 +6,22 @@ */ function alternatingCharacters(string) { - let prev = ''; - let counter = 0; - for (let index = 0; index < string.length; index++) { - if(!prev){ - prev = string[index]; - continue; - } + let prev = ''; + let counter = 0; + for (let index = 0; index < string.length; index++) { + if (!prev) { + prev = string[index]; + continue; + } - if(prev === string[index]){ - counter++; - } + if (prev === string[index]) { + counter++; + } - prev = string[index]; - } + prev = string[index]; + } - return counter; + return counter; } console.log(alternatingCharacters('BBBBB')); diff --git a/src/Strings/counting-valleys.js b/src/Strings/counting-valleys.js index dbb44ae..79459ab 100644 --- a/src/Strings/counting-valleys.js +++ b/src/Strings/counting-valleys.js @@ -5,23 +5,21 @@ Link: https://www.hackerrank.com/challenges/counting-valleys */ -function countingValleys(n, s) { - let currentValley = 0; - let count = 0; - for (let i = 0; i < n; i++) { +module.exports = function countingValleys(n, s) { + let currentValley = 0; + let count = 0; + for (let i = 0; i < n; i++) { + if (s[i] === 'U') { + currentValley++; + } + if (s[i] === 'D') { + currentValley--; + } - if (s[i] === 'U') { - currentValley++; - } - if (s[i] === 'D') { - currentValley--; - } + if (currentValley === '0' && s[i] === 'U') { + count++; + } + } - if (currentValley == 0 && s[i] === 'U') { - count++; - } - } - - return count; - -} + return count; +}; diff --git a/src/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js index 1e8ebbd..2564590 100644 --- a/src/Strings/hackerrank-in-string.js +++ b/src/Strings/hackerrank-in-string.js @@ -6,12 +6,12 @@ */ module.exports = function hackerrankInString(s) { - const mask = Array.from("hackerrank"); - for (let i = 0; i < s.length; i++) { - const currentChar = s.charAt(i); - if (mask[0] === currentChar) { - mask.shift(); - } - } - return mask.length === 0 ? "YES" : "NO"; + const mask = Array.from('hackerrank'); + for (let i = 0; i < s.length; i++) { + const currentChar = s.charAt(i); + if (mask[0] === currentChar) { + mask.shift(); + } + } + return mask.length === 0 ? 'YES' : 'NO'; }; diff --git a/src/Strings/making-anagrams.js b/src/Strings/making-anagrams.js index 4de1579..864472a 100644 --- a/src/Strings/making-anagrams.js +++ b/src/Strings/making-anagrams.js @@ -5,46 +5,44 @@ Link: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_r=internal-search */ - -function makeAnagram(string1, string2){ - string1 = count(string1); - string2 = count(string2); - return findDiff(string1, string2); -} - function count(a) { - let arr = a.split('').sort(); - let counter = {}; - arr.forEach(value => { - if (counter[value] !== undefined) { - counter[value] += 1; - } else { - counter[value] = 1; - } - }) - - return counter; + const arr = a.split('').sort(); + const counter = {}; + arr.forEach((value) => { + if (counter[value] !== undefined) { + counter[value] += 1; + } else { + counter[value] = 1; + } + }); + + return counter; } function findDiff(arr1, arr2) { - let removeCount = 0; - - for (let key in arr1) { - if (!arr2[key]) { - removeCount += arr1[key]; - } else { - removeCount += Math.abs(arr2[key] - arr1[key]); - } - } - - for (let key in arr2) { - if (!arr1[key]) { - removeCount += arr2[key]; - } - } - return removeCount; + let removeCount = 0; + + for (const key in arr1) { + if (!arr2[key]) { + removeCount += arr1[key]; + } else { + removeCount += Math.abs(arr2[key] - arr1[key]); + } + } + + for (const key in arr2) { + if (!arr1[key]) { + removeCount += arr2[key]; + } + } + return removeCount; +} +function makeAnagram(string1, string2) { + string1 = count(string1); + string2 = count(string2); + return findDiff(string1, string2); } -let a = "fcrxzwscanmligyxyvym"; -let b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; -console.log(makeAnagram(a,b )); +const a = 'fcrxzwscanmligyxyvym'; +const b = 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'; +console.log(makeAnagram(a, b)); diff --git a/src/Strings/repeated-string.js b/src/Strings/repeated-string.js index 4497df6..6e71159 100644 --- a/src/Strings/repeated-string.js +++ b/src/Strings/repeated-string.js @@ -6,11 +6,11 @@ */ module.exports = function repeatedString(s, n) { - let initialCount = s.split('a').length - 1; - let cocent = Math.floor(n / s.length); - let total = cocent * initialCount; - let remainder = n % s.length; - let remaindLetter = s.slice(0, remainder); - total += remaindLetter.split('a').length - 1; - return total; -} + const initialCount = s.split('a').length - 1; + const cocent = Math.floor(n / s.length); + let total = cocent * initialCount; + const remainder = n % s.length; + const remaindLetter = s.slice(0, remainder); + total += remaindLetter.split('a').length - 1; + return total; +}; diff --git a/src/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js index 5846fcf..d786906 100644 --- a/src/Strings/sherlock-and-the-valid-string.js +++ b/src/Strings/sherlock-and-the-valid-string.js @@ -6,36 +6,35 @@ */ function isValid(string) { - let counter = {}; - - let arr = string.split('').sort(); - let smallValue = 0; - let allowedTimes = 0; - arr.forEach(element => { - counter[element] = counter[element] === undefined ? 1 : counter[element]+1; - }); - - for(let key in counter){ - if(smallValue === 0){ - smallValue = counter[key]; - continue ; - } - - if(smallValue !== counter[key]){ - if(counter[key] === 1){ - allowedTimes += 1; - } else { - allowedTimes += Math.abs(smallValue - counter[key]); - } - } - - if(allowedTimes > 1){ - break; - } - } - - return allowedTimes > 1 ? false : true; + const counter = {}; + + const arr = string.split('').sort(); + let smallValue = 0; + let allowedTimes = 0; + arr.forEach((element) => { + counter[element] = counter[element] === undefined ? 1 : counter[element] + 1; + }); + + for (const key in counter) { + if (smallValue === 0) { + smallValue = counter[key]; + continue; + } + + if (smallValue !== counter[key]) { + if (counter[key] === 1) { + allowedTimes += 1; + } else { + allowedTimes += Math.abs(smallValue - counter[key]); + } + } + + if (allowedTimes > 1) { + break; + } + } + + return !(allowedTimes > 1); } - -console.log(isValid("abcdefghhgfedecba")); +console.log(isValid('abcdefghhgfedecba')); diff --git a/src/Strings/strong-password.js b/src/Strings/strong-password.js index d3fd7c0..fa54fb6 100644 --- a/src/Strings/strong-password.js +++ b/src/Strings/strong-password.js @@ -6,27 +6,21 @@ */ module.exports = function passwordStrengthMinimumNumber(n, password) { - const STRONG_LENGTH = 6; - const missingChars = STRONG_LENGTH - n; - let score = 0; + const STRONG_LENGTH = 6; + const missingChars = STRONG_LENGTH - n; + let score = 0; - const passwordAsArray = Array.from(password); + const passwordAsArray = Array.from(password); - const hasNumber = passwordAsArray.some(char => "0123456789".includes(char)); - const hasLowerCase = passwordAsArray.some(char => - "abcdefghijklmnopqrstuvwxyz".includes(char) - ); - const hasUpperCase = passwordAsArray.some(char => - "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(char) - ); - const hasSpecialChar = passwordAsArray.some(char => - "!@#$%^&*()-+".includes(char) - ); + const hasNumber = passwordAsArray.some((char) => '0123456789'.includes(char)); + const hasLowerCase = passwordAsArray.some((char) => 'abcdefghijklmnopqrstuvwxyz'.includes(char)); + const hasUpperCase = passwordAsArray.some((char) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(char)); + const hasSpecialChar = passwordAsArray.some((char) => '!@#$%^&*()-+'.includes(char)); - if (!hasNumber) score++; - if (!hasLowerCase) score++; - if (!hasUpperCase) score++; - if (!hasSpecialChar) score++; + if (!hasNumber) score++; + if (!hasLowerCase) score++; + if (!hasUpperCase) score++; + if (!hasSpecialChar) score++; - return Math.max(score, missingChars); + return Math.max(score, missingChars); }; diff --git a/src/Strings/time-conversion.js b/src/Strings/time-conversion.js index 6cabfbc..dc86243 100644 --- a/src/Strings/time-conversion.js +++ b/src/Strings/time-conversion.js @@ -5,24 +5,23 @@ Link: https://www.hackerrank.com/challenges/time-conversion/ */ - module.exports = function timeConversion(time) { - let cycle = time.substring(time.length - 2, time.length); - let timeWithoutCycle = time.substring(0, time.length - 2); - let timeArr = timeWithoutCycle.split(':'); + const cycle = time.substring(time.length - 2, time.length); + const timeWithoutCycle = time.substring(0, time.length - 2); + const timeArr = timeWithoutCycle.split(':'); - if (cycle === 'AM') { - if (timeArr[0] != 12) { - return timeWithoutCycle; - } + if (cycle === 'AM') { + if (timeArr[0] !== '12') { + return timeWithoutCycle; + } - timeArr[0] = '00'; - return timeArr.join(':'); - } + timeArr[0] = '00'; + return timeArr.join(':'); + } - if (timeArr[0] != 12) { - timeArr[0] = parseInt(timeArr[0]) + 12; - } + if (timeArr[0] !== '12') { + timeArr[0] = parseInt(timeArr[0], 10) + 12; + } - return timeArr.join(':') -} + return timeArr.join(':'); +}; diff --git a/test/Arrays/birthday-cake-candles.test.js b/test/Arrays/birthday-cake-candles.test.js index 5d43aba..506cc68 100644 --- a/test/Arrays/birthday-cake-candles.test.js +++ b/test/Arrays/birthday-cake-candles.test.js @@ -1,28 +1,28 @@ -const birthdayCakeCandles = require("../../src/Arrays/birthday-cake-candles"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const birthdayCakeCandles = require('../../src/Arrays/birthday-cake-candles'); -describe("Birthday Cake Candles", () => { - it("returns 0 for empty array", () => { - expect(birthdayCakeCandles([])).to.equal(0); - }); +describe('Birthday Cake Candles', () => { + it('returns 0 for empty array', () => { + expect(birthdayCakeCandles([])).to.equal(0); + }); - it("returns 1 if there is only one candle", () => { - expect(birthdayCakeCandles([1])).to.equal(1); - expect(birthdayCakeCandles([2])).to.equal(1); - expect(birthdayCakeCandles([3])).to.equal(1); - }); + it('returns 1 if there is only one candle', () => { + expect(birthdayCakeCandles([1])).to.equal(1); + expect(birthdayCakeCandles([2])).to.equal(1); + expect(birthdayCakeCandles([3])).to.equal(1); + }); - it("returns 2 if there are two candles with the same height", () => { - expect(birthdayCakeCandles([1, 1])).to.equal(2); - expect(birthdayCakeCandles([2, 2])).to.equal(2); - expect(birthdayCakeCandles([3, 3])).to.equal(2); - }); + it('returns 2 if there are two candles with the same height', () => { + expect(birthdayCakeCandles([1, 1])).to.equal(2); + expect(birthdayCakeCandles([2, 2])).to.equal(2); + expect(birthdayCakeCandles([3, 3])).to.equal(2); + }); - it("returns correct amount for array with different sized candles", () => { - expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); - expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); - expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); - expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); - }); + it('returns correct amount for array with different sized candles', () => { + expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); + expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); + expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); + expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); + }); }); diff --git a/test/Arrays/left-rotation.test.js b/test/Arrays/left-rotation.test.js index 2a4e66a..0965ab2 100644 --- a/test/Arrays/left-rotation.test.js +++ b/test/Arrays/left-rotation.test.js @@ -1,22 +1,20 @@ -const leftRotation = require('../../src/Arrays/left-rotation') -const { describe, it } = require('mocha') -const { expect } = require('chai') +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const leftRotation = require('../../src/Arrays/left-rotation'); describe('Left Rotation', () => { + it('should work for any empty array', () => { + expect(leftRotation([], 10)).to.deep.equal([]); + }); - it('should work for any empty array', () => { - expect(leftRotation([], 10)).to.deep.equal([]) - }) + it('should work for a 1 element array', () => { + const original = [1]; + expect(leftRotation(original, 10)).to.deep.equal(original); + }); - it('should work for a 1 element array', () => { - const original = [1] - expect(leftRotation(original, 10)).to.deep.equal(original) - }) - - it('should work for multiple elements', () => { - const original = "ABCDEF".split('') - const expected = "DEFABC".split('') - expect(leftRotation(original, 3)).to.deep.equal(expected) - }) - -}) + it('should work for multiple elements', () => { + const original = 'ABCDEF'.split(''); + const expected = 'DEFABC'.split(''); + expect(leftRotation(original, 3)).to.deep.equal(expected); + }); +}); diff --git a/test/Data Structures/cycle-detection.test.js b/test/Data Structures/cycle-detection.test.js index 32fdcb7..24bbb2e 100644 --- a/test/Data Structures/cycle-detection.test.js +++ b/test/Data Structures/cycle-detection.test.js @@ -1,54 +1,54 @@ -const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); const { describe, it } = require('mocha'); const { expect } = require('chai'); +const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); describe('Cycle Detection', () => { - it('should detect a cycle in a regular linked list', () => { - const test1 = new Node(1); - const tail1 = test1.insert(2) // tail1 === Node #8 - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - const connection1 = test1.next.next.next; // connection1 === Node #4 - tail1.next = connection1; - expect(hasCycle(test1)).to.equal(true); - }); + it('should detect a cycle in a regular linked list', () => { + const test1 = new Node(1); + const tail1 = test1.insert(2) // tail1 === Node #8 + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + const connection1 = test1.next.next.next; // connection1 === Node #4 + tail1.next = connection1; + expect(hasCycle(test1)).to.equal(true); + }); - it('should return false when the end of the list points to null', () => { - const test2 = new Node(1); - test2.insert(2) - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - expect(hasCycle(test2)).to.equal(false); - }); + it('should return false when the end of the list points to null', () => { + const test2 = new Node(1); + test2.insert(2) + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + expect(hasCycle(test2)).to.equal(false); + }); - it('should return false when head is null instead of a node', () => { - const test3 = null; - expect(hasCycle(test3)).to.equal(false); - }); + it('should return false when head is null instead of a node', () => { + const test3 = null; + expect(hasCycle(test3)).to.equal(false); + }); - it('should return false when the linked list only has one node that points to null', () => { - const test4 = new Node(1); - expect(hasCycle(test4)).to.equal(false); - }); + it('should return false when the linked list only has one node that points to null', () => { + const test4 = new Node(1); + expect(hasCycle(test4)).to.equal(false); + }); - it('should return false when the linked list only has two nodes', () => { - const test5 = new Node(1); - test5.insert(2); - expect(hasCycle(test5)).to.equal(false); - }); + it('should return false when the linked list only has two nodes', () => { + const test5 = new Node(1); + test5.insert(2); + expect(hasCycle(test5)).to.equal(false); + }); - it('should return false when the linked list only has two nodes but the tail links to head', () => { - const test6 = new Node(1); - const tail6 = test6.insert(2); // tail6 === Node #2 - tail6.next = test6; - expect(hasCycle(test6)).to.equal(true); - }); -}) + it('should return false when the linked list only has two nodes but the tail links to head', () => { + const test6 = new Node(1); + const tail6 = test6.insert(2); // tail6 === Node #2 + tail6.next = test6; + expect(hasCycle(test6)).to.equal(true); + }); +}); diff --git a/test/Data Structures/reverse-doubly-linked-list.test.js b/test/Data Structures/reverse-doubly-linked-list.test.js index 4acc443..7545ba3 100644 --- a/test/Data Structures/reverse-doubly-linked-list.test.js +++ b/test/Data Structures/reverse-doubly-linked-list.test.js @@ -1,29 +1,28 @@ +const { describe, it } = require('mocha'); +const { expect } = require('chai'); const { reverse, DoublyLinkedListNode, DoublyLinkedList } = require('../../src/Data Structures/reverse-doubly-linked-list'); -const { describe, it } = require('mocha') -const { expect } = require('chai') - describe('Reverse Doubly Linked List', () => { - it('should reverse an empty list', () => { - let node = new DoublyLinkedListNode(1) - expect(reverse(node)).to.deep.equal(node) - }) + it('should reverse an empty list', () => { + const node = new DoublyLinkedListNode(1); + expect(reverse(node)).to.deep.equal(node); + }); - it('should reverse a chain of linked nodes', () => { - let list = new DoublyLinkedList(); - list.insertNode(1) - list.insertNode(2) - list.insertNode(3) - list.insertNode(4) - list.insertNode(5) + it('should reverse a chain of linked nodes', () => { + const list = new DoublyLinkedList(); + list.insertNode(1); + list.insertNode(2); + list.insertNode(3); + list.insertNode(4); + list.insertNode(5); - let reversedList = new DoublyLinkedList(); - reversedList.insertNode(5) - reversedList.insertNode(4) - reversedList.insertNode(3) - reversedList.insertNode(2) - reversedList.insertNode(1) + const reversedList = new DoublyLinkedList(); + reversedList.insertNode(5); + reversedList.insertNode(4); + reversedList.insertNode(3); + reversedList.insertNode(2); + reversedList.insertNode(1); - expect(reverse(list.head)).to.deep.equal(reversedList.head) - }) -}) \ No newline at end of file + expect(reverse(list.head)).to.deep.equal(reversedList.head); + }); +}); diff --git a/test/Numbers/plus-minus.test.js b/test/Numbers/plus-minus.test.js index 7fa3ced..86cc971 100644 --- a/test/Numbers/plus-minus.test.js +++ b/test/Numbers/plus-minus.test.js @@ -1,17 +1,17 @@ -const plusMinus = require('../../src/Numbers/plus-minus') -const { describe, it } = require('mocha') -const { expect } = require('chai') +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const plusMinus = require('../../src/Numbers/plus-minus'); describe('Plus Minus Problem', () => { - it('It should Return 2 Positive 2 Negative and 1 Zero', () => { - expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({positive: 2, negative: 2, zero: 1 }); - }); + it('It should Return 2 Positive 2 Negative and 1 Zero', () => { + expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({ positive: 2, negative: 2, zero: 1 }); + }); - it('It should Return 5 Positive', () => { - expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({positive: 5, negative: 0, zero: 0 }); - }); + it('It should Return 5 Positive', () => { + expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({ positive: 5, negative: 0, zero: 0 }); + }); - it('It should Return 5 Negative', () => { - expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({positive: 0, negative: 5, zero: 0 }); - }); -}) + it('It should Return 5 Negative', () => { + expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({ positive: 0, negative: 5, zero: 0 }); + }); +}); diff --git a/test/Strings/hackerrank-in-string.test.js b/test/Strings/hackerrank-in-string.test.js index 349627c..fdbd886 100644 --- a/test/Strings/hackerrank-in-string.test.js +++ b/test/Strings/hackerrank-in-string.test.js @@ -1,28 +1,24 @@ -const hackerrankInString = require("../../src/Strings/hackerrank-in-string"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const hackerrankInString = require('../../src/Strings/hackerrank-in-string'); -describe("HackerRank in a String", () => { - it("should return NO for any empty string", () => { - expect(hackerrankInString("")).to.equal("NO"); - }); +describe('HackerRank in a String', () => { + it('should return NO for any empty string', () => { + expect(hackerrankInString('')).to.equal('NO'); + }); - it("should return YES for an exact match", () => { - expect(hackerrankInString("hackerrank")).to.equal("YES"); - }); + it('should return YES for an exact match', () => { + expect(hackerrankInString('hackerrank')).to.equal('YES'); + }); - describe("should return YES inputs containing hackerrank", () => { - it("hereiamstackerrank", () => - expect(hackerrankInString("hereiamstackerrank")).to.equal("YES")); - it("hhaacckkekraraannk", () => - expect(hackerrankInString("hhaacckkekraraannk")).to.equal("YES")); - }); - describe("should return NO for inputs that don't contain hackerrank", () => { - it("hackerworld", () => - expect(hackerrankInString("hackerworld")).to.equal("NO")); - it("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt", () => - expect( - hackerrankInString("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt") - ).to.equal("NO")); - }); + describe('should return YES inputs containing hackerrank', () => { + it('hereiamstackerrank', () => expect(hackerrankInString('hereiamstackerrank')).to.equal('YES')); + it('hhaacckkekraraannk', () => expect(hackerrankInString('hhaacckkekraraannk')).to.equal('YES')); + }); + describe("should return NO for inputs that don't contain hackerrank", () => { + it('hackerworld', () => expect(hackerrankInString('hackerworld')).to.equal('NO')); + it('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt', () => expect( + hackerrankInString('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt'), + ).to.equal('NO')); + }); }); diff --git a/test/Strings/repeated-string.test.js b/test/Strings/repeated-string.test.js index 7003391..0dd8a47 100644 --- a/test/Strings/repeated-string.test.js +++ b/test/Strings/repeated-string.test.js @@ -1,25 +1,25 @@ -const repeatedString = require("../../src/Strings/repeated-string"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const repeatedString = require('../../src/Strings/repeated-string'); -describe("Repeated String", () => { - it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { - expect(repeatedString("aba", 10)).to.eq(7); - }); +describe('Repeated String', () => { + it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { + expect(repeatedString('aba', 10)).to.eq(7); + }); - it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { - expect(repeatedString("aaaaaa", 1)).to.eq(1); - }); + it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { + expect(repeatedString('aaaaaa', 1)).to.eq(1); + }); - it("should return n if input string is 'a'", () => { - expect(repeatedString("a", 100000)).to.eq(100000); - expect(repeatedString("a", 300)).to.eq(300); - expect(repeatedString("a", 5)).to.eq(5); - }); + it("should return n if input string is 'a'", () => { + expect(repeatedString('a', 100000)).to.eq(100000); + expect(repeatedString('a', 300)).to.eq(300); + expect(repeatedString('a', 5)).to.eq(5); + }); - it("should return 0 if the input string does not contain 'a'", () => { - expect(repeatedString("test", 20)).to.eq(0); - expect(repeatedString("bbbb", 7)).to.eq(0); - expect(repeatedString("cdcdcd", 5)).to.eq(0); - }); + it("should return 0 if the input string does not contain 'a'", () => { + expect(repeatedString('test', 20)).to.eq(0); + expect(repeatedString('bbbb', 7)).to.eq(0); + expect(repeatedString('cdcdcd', 5)).to.eq(0); + }); }); diff --git a/test/Strings/strong-password.test.js b/test/Strings/strong-password.test.js index f9fec61..4e70cfc 100644 --- a/test/Strings/strong-password.test.js +++ b/test/Strings/strong-password.test.js @@ -1,26 +1,19 @@ -const passwordStrengthMinimumNumber = require("../../src/Strings/strong-password"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const passwordStrengthMinimumNumber = require('../../src/Strings/strong-password'); -describe("Strong Password", () => { - it("returns 6 for empty string", () => - expect(passwordStrengthMinimumNumber(0, "")).to.equal(6)); +describe('Strong Password', () => { + it('returns 6 for empty string', () => expect(passwordStrengthMinimumNumber(0, '')).to.equal(6)); - it("returns 3 with password length of 3", () => - expect(passwordStrengthMinimumNumber(3, "Ab1")).to.equal(3)); + it('returns 3 with password length of 3', () => expect(passwordStrengthMinimumNumber(3, 'Ab1')).to.equal(3)); - it("returns 3 with missing special character, number and uppercase letter", () => - expect(passwordStrengthMinimumNumber(3, "longenough")).to.equal(3)); + it('returns 3 with missing special character, number and uppercase letter', () => expect(passwordStrengthMinimumNumber(3, 'longenough')).to.equal(3)); - it("returns 1 with missing number", () => - expect(passwordStrengthMinimumNumber(11, "#HackerRank")).to.equal(1)); + it('returns 1 with missing number', () => expect(passwordStrengthMinimumNumber(11, '#HackerRank')).to.equal(1)); - it("returns 1 with missing special character", () => - expect(passwordStrengthMinimumNumber(11, "1HackerRank")).to.equal(1)); + it('returns 1 with missing special character', () => expect(passwordStrengthMinimumNumber(11, '1HackerRank')).to.equal(1)); - it("returns 1 with missing uppercase letter", () => - expect(passwordStrengthMinimumNumber(12, "#1hackerrank")).to.equal(1)); + it('returns 1 with missing uppercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1hackerrank')).to.equal(1)); - it("returns 1 with missing lowercase letter", () => - expect(passwordStrengthMinimumNumber(12, "#1HACKERRANK")).to.equal(1)); + it('returns 1 with missing lowercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1HACKERRANK')).to.equal(1)); }); diff --git a/test/Strings/time-conversion.test.js b/test/Strings/time-conversion.test.js index 16ba822..5e940bc 100644 --- a/test/Strings/time-conversion.test.js +++ b/test/Strings/time-conversion.test.js @@ -1,21 +1,21 @@ -const timeConversion = require("../../src/Strings/time-conversion"); -const { describe, it } = require("mocha"); -const { expect } = require("chai"); +const { describe, it } = require('mocha'); +const { expect } = require('chai'); +const timeConversion = require('../../src/Strings/time-conversion'); -describe("Time Conversion", () => { - it("should convert midnight", () => { - expect(timeConversion("12:00:00AM")).to.eq("00:00:00") - }); +describe('Time Conversion', () => { + it('should convert midnight', () => { + expect(timeConversion('12:00:00AM')).to.eq('00:00:00'); + }); - it("should convert noon", () => { - expect(timeConversion("12:00:00PM")).to.eq("12:00:00") - }); + it('should convert noon', () => { + expect(timeConversion('12:00:00PM')).to.eq('12:00:00'); + }); - it("should convert an AM time", () => { - expect(timeConversion("07:05:45AM")).to.eq("07:05:45") - }); + it('should convert an AM time', () => { + expect(timeConversion('07:05:45AM')).to.eq('07:05:45'); + }); - it("should convert a PM time", () => { - expect(timeConversion("07:05:45PM")).to.eq("19:05:45") - }); -}); \ No newline at end of file + it('should convert a PM time', () => { + expect(timeConversion('07:05:45PM')).to.eq('19:05:45'); + }); +}); From e70f197e2e0edb9a2dbb14f9979e49923d6a84e4 Mon Sep 17 00:00:00 2001 From: sandhyak-tech Date: Fri, 29 Oct 2021 00:06:58 +0530 Subject: [PATCH 8/8] Revert "Fix Build errors" This reverts commit d9e5dfc509068d2dff7a1a21aebf1c047fb05cb0. --- src/Arrays/2d-array-ds.js | 22 ++--- src/Arrays/apple-and-orange.js | 27 +++--- src/Arrays/array-manipulation.js | 18 ++-- src/Arrays/birthday-cake-candles.js | 24 ++--- src/Arrays/breaking-best-and-worst-records.js | 62 ++++++------- src/Arrays/compare-the-triplets.js | 20 ++--- src/Arrays/diagonal-difference.js | 21 ++--- src/Arrays/jumping-on-the-clouds.js | 31 +++---- src/Arrays/left-rotation.js | 17 ++-- src/Arrays/minimum-swaps-2.js | 35 ++++---- src/Arrays/newyear-chaos.js | 36 ++++---- src/Arrays/sock-merchant.js | 36 ++++---- src/Data Structures/cycle-detection.js | 39 ++++---- .../reverse-doubly-linked-list.js | 85 +++++++++--------- .../count-triplet.js | 37 ++++---- .../custom-hashmap.js | 40 ++++----- .../frequency-queries.js | 58 ++++++------ .../game-of-thrones.js | 14 +-- src/Dictionaries and Hashmaps/ransom-note.js | 71 ++++++++------- .../sherlock-and-anagrams.js | 32 +++---- src/Dictionaries and Hashmaps/two-strings.js | 25 +++--- src/Numbers/grading.js | 27 +++--- src/Numbers/kangaroo.js | 44 ++++----- src/Numbers/plus-minus.js | 34 +++---- src/Numbers/staircase.js | 8 +- src/Sorting/bubble-sort.js | 30 +++---- src/Sorting/mark-and-toys.js | 28 +++--- src/Sorting/mini-max-sum.js | 14 +-- src/Strings/alternating-characters.js | 26 +++--- src/Strings/counting-valleys.js | 34 +++---- src/Strings/hackerrank-in-string.js | 16 ++-- src/Strings/making-anagrams.js | 72 +++++++-------- src/Strings/repeated-string.js | 16 ++-- src/Strings/sherlock-and-the-valid-string.js | 61 ++++++------- src/Strings/strong-password.js | 32 ++++--- src/Strings/time-conversion.js | 31 +++---- test/Arrays/birthday-cake-candles.test.js | 46 +++++----- test/Arrays/left-rotation.test.js | 34 +++---- test/Data Structures/cycle-detection.test.js | 90 +++++++++---------- .../reverse-doubly-linked-list.test.js | 45 +++++----- test/Numbers/plus-minus.test.js | 26 +++--- test/Strings/hackerrank-in-string.test.js | 44 ++++----- test/Strings/repeated-string.test.js | 40 ++++----- test/Strings/strong-password.test.js | 29 +++--- test/Strings/time-conversion.test.js | 34 +++---- 45 files changed, 829 insertions(+), 782 deletions(-) diff --git a/src/Arrays/2d-array-ds.js b/src/Arrays/2d-array-ds.js index 6bb6e73..1e5a28e 100644 --- a/src/Arrays/2d-array-ds.js +++ b/src/Arrays/2d-array-ds.js @@ -4,14 +4,14 @@ Score: 15 Link: https://www.hackerrank.com/challenges/2d-array/ */ -module.exports = function hourglassSum(arr) { - let sum = -1000; - let max = sum; - for (let i = 0; i < 4; i++) { - for (let j = 0; j < 4; j++) { - sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; - if (sum > max) max = sum; - } - } - console.log(max); -}; +function hourglassSum(arr) { + var sum = -1000 + let max = sum + for(let i = 0 ; i<4;i++){ + for(let j = 0 ; j<4; j++){ + sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] + if(sum>max) max = sum + } + } + console.log(max) +} diff --git a/src/Arrays/apple-and-orange.js b/src/Arrays/apple-and-orange.js index 6574de8..ffaf16a 100644 --- a/src/Arrays/apple-and-orange.js +++ b/src/Arrays/apple-and-orange.js @@ -5,21 +5,22 @@ Link: https://www.hackerrank.com/challenges/apple-and-orange */ +function countApplesAndOranges(s, t, a, b, apples, oranges) { + countFruitsFallInsideHome(apples, s - a, t - a); + countFruitsFallInsideHome(oranges, s - b, t - b); +} + + function countFruitsFallInsideHome(fruits, startHome, EndHome) { - let counter = 0; - fruits.forEach((fruit) => { - if (fruit >= startHome && fruit <= EndHome) { - counter++; - } - return counter; - }); + let counter = 0; + fruits.forEach(fruit => { + if (fruit >= startHome && fruit <= EndHome) { + return counter++; + } + }); - return console.log(counter); + return console.log(counter); } -function countApplesAndOranges(s, t, a, b, apples, oranges) { - countFruitsFallInsideHome(apples, s - a, t - a); - countFruitsFallInsideHome(oranges, s - b, t - b); -} +countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1] , [5 -6]); -countApplesAndOranges(7, 11, 5, 15, 3, 2, [-2, 2, 1], [5 - 6]); diff --git a/src/Arrays/array-manipulation.js b/src/Arrays/array-manipulation.js index a04ae2b..45eaf1d 100644 --- a/src/Arrays/array-manipulation.js +++ b/src/Arrays/array-manipulation.js @@ -5,14 +5,14 @@ Link: https://www.hackerrank.com/challenges/crush/problem */ -module.exports = function arrayManipulation(n, queries) { - const arr = Array(n).fill(0); +function arrayManipulation(n, queries) { + let arr = Array(n).fill(0); - for (let a = 0; a < queries.length; a++) { - for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { - arr[index] += queries[a][2]; - } - } + for (let a = 0; a < queries.length; a++) { + for (let index = queries[a][0] - 1; index < queries[a][1]; index++) { + arr[index] += queries[a][2]; + } + } - return Math.max(...arr); -}; + return Math.max(...arr); +} diff --git a/src/Arrays/birthday-cake-candles.js b/src/Arrays/birthday-cake-candles.js index 674311e..35ed0d7 100644 --- a/src/Arrays/birthday-cake-candles.js +++ b/src/Arrays/birthday-cake-candles.js @@ -6,16 +6,16 @@ */ module.exports = function birthdayCakeCandles(arr) { - let tallestCandle = 0; - let candlesCounter = 0; - for (let index = 0; index < arr.length; index++) { - if (arr[index] > tallestCandle) { - tallestCandle = arr[index]; - candlesCounter = 1; - } else if (arr[index] === tallestCandle) { - candlesCounter++; - } - } + let tallestCandle = 0; + let candlesCounter = 0; + for (let index = 0; index < arr.length; index++) { + if (arr[index] > tallestCandle) { + tallestCandle = arr[index]; + candlesCounter = 1; + } else if (arr[index] === tallestCandle) { + candlesCounter++; + } + } - return candlesCounter; -}; + return candlesCounter; +} diff --git a/src/Arrays/breaking-best-and-worst-records.js b/src/Arrays/breaking-best-and-worst-records.js index 9df7f33..1afad77 100644 --- a/src/Arrays/breaking-best-and-worst-records.js +++ b/src/Arrays/breaking-best-and-worst-records.js @@ -6,35 +6,37 @@ */ function breakingRecords(scores) { - const counters = { - min: 0, - max: 0, - }; - - const values = { - min: 0, - max: 0, - }; - let isDefaultSet = false; - - scores.forEach((score) => { - if (!isDefaultSet) { - values.min = score; - values.max = score; - isDefaultSet = true; - return; - } - - if (score > values.max) { - values.max = score; - counters.max++; - } else if (score < values.min) { - values.min = score; - counters.min++; - } - }); - - return [counters.max, counters.min]; + + let counters = { + min: 0, + max: 0 + }; + + let values = { + min: 0, + max: 0 + } + let isDefaultSet = false; + + scores.forEach(score => { + if (!isDefaultSet) { + values.min = score; + values.max = score; + isDefaultSet = true; + return ; + } + + if (score > values.max) { + values.max = score; + counters.max++; + } else if (score < values.min) { + values.min = score; + counters.min++; + } + }) + + return [counters.max, counters.min]; + } -breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]); +breakingRecords([10, 5, 20, 20, 4, 5, 2, 25, 1]) diff --git a/src/Arrays/compare-the-triplets.js b/src/Arrays/compare-the-triplets.js index b542423..75d6007 100644 --- a/src/Arrays/compare-the-triplets.js +++ b/src/Arrays/compare-the-triplets.js @@ -6,16 +6,16 @@ Link: https://www.hackerrank.com/challenges/compare-the-triplets/problem */ function compareTriplets(a, b) { - const points = [0, 0]; - for (let index = 0; index < a.length; index++) { - if (a[index] > b[index]) { - points[0] += 1; - } else if (a[index] < b[index]) { - points[1] += 1; - } - } + let points = [0, 0]; + for (let index = 0; index < a.length; index++){ + if (a[index] > b[index]) { + points[0] += 1; + } else if (a[index] < b[index]) { + points[1] += 1; + } + } - return points; + return points; } -console.log(compareTriplets([5, 6, 7], [3, 6, 10])); +console.log(compareTriplets([5, 6, 7], [3, 6, 10])) diff --git a/src/Arrays/diagonal-difference.js b/src/Arrays/diagonal-difference.js index 5304e9e..336b05d 100644 --- a/src/Arrays/diagonal-difference.js +++ b/src/Arrays/diagonal-difference.js @@ -1,3 +1,4 @@ + /* Title:Diagonal Difference Difficulty: Easy @@ -6,16 +7,16 @@ */ function diagonalDifference(arr) { - let leftToRight = 0; - let rightToLeft = 0; - let tmpLength = arr.length; - for (let i = 0; i < arr.length; i++) { - leftToRight += arr[i][i]; - rightToLeft += arr[i][--tmpLength]; - } + let leftToRight = 0; + let rightToLeft = 0; + let tmpLength = arr.length; + for (let i = 0; i < arr.length; i++){ + leftToRight += arr[i][i]; + rightToLeft += arr[i][--tmpLength]; + } - return Math.abs(leftToRight - rightToLeft); + return Math.abs(leftToRight - rightToLeft); } -const input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]; -console.log(diagonalDifference(input)); +let input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]] +console.log(diagonalDifference(input)) diff --git a/src/Arrays/jumping-on-the-clouds.js b/src/Arrays/jumping-on-the-clouds.js index 5a4095a..9f5c7d1 100644 --- a/src/Arrays/jumping-on-the-clouds.js +++ b/src/Arrays/jumping-on-the-clouds.js @@ -5,19 +5,20 @@ Link: https://www.hackerrank.com/challenges/jumping-on-the-clouds/ */ -module.exports = function jumpingOnClouds(c) { - let jump = 0; - for (let i = 0; i < c.length;) { - if (c[i + 2] === '0') { - jump++; - i += 2; - } else if (c[i + 1] === '0') { - jump++; - i += 1; - } else { - i++; - } - } +function jumpingOnClouds(c) { - return jump; -}; + let jump = 0; + for (let i = 0; i < c.length;){ + if (c[i + 2] == 0) { + jump++; + i += 2; + } else if (c[i + 1] == 0) { + jump++; + i += 1; + } else { + i++; + } + } + + return jump; +} diff --git a/src/Arrays/left-rotation.js b/src/Arrays/left-rotation.js index 7881ba7..17ed7de 100644 --- a/src/Arrays/left-rotation.js +++ b/src/Arrays/left-rotation.js @@ -6,13 +6,14 @@ */ module.exports = function rotLeft(a, d) { - if (!a.length) { - return []; - } - for (let i = 0; i < d; i++) { - a.push(a.shift()); - } + if(!a.length){ + return [] + } - return a; -}; + for (let i = 0; i < d; i++) { + a.push(a.shift()); + } + + return a; +} diff --git a/src/Arrays/minimum-swaps-2.js b/src/Arrays/minimum-swaps-2.js index 95c93fc..c382556 100644 --- a/src/Arrays/minimum-swaps-2.js +++ b/src/Arrays/minimum-swaps-2.js @@ -5,21 +5,22 @@ Link: https://www.hackerrank.com/challenges/minimum-swaps-2 */ -module.exports = function minimumSwaps(arr) { - const origArray = arr.slice(0); - const sortedArray = arr.sort((a, b) => a - b); - let numberOfSwap = 0; - for (let i = 0; i < origArray.length; i++) { - if (origArray[i] !== sortedArray[i]) { - for (let j = i + 1; j < origArray.length; j++) { - if (origArray[j] === sortedArray[i]) { - [origArray[i], origArray[j]] = [origArray[j], origArray[i]]; - numberOfSwap++; - break; - } - } - } - } - return numberOfSwap; -}; +function minimumSwaps(arr) { + var origArray = arr.slice(0); + var sortedArray = arr.sort((a,b) => a-b); + let numberOfSwap = 0; + for (var i = 0; i < origArray.length; i++) { + if (origArray[i] != sortedArray[i]) { + for (var j = i + 1; j < origArray.length; j++) { + if (origArray[j] === sortedArray[i]) { + [origArray[i], origArray[j]] = [origArray[j], origArray[i]] + numberOfSwap++ + break; + } + } + } + } + + return numberOfSwap; +} diff --git a/src/Arrays/newyear-chaos.js b/src/Arrays/newyear-chaos.js index 08eb21a..0ae6270 100644 --- a/src/Arrays/newyear-chaos.js +++ b/src/Arrays/newyear-chaos.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/new-year-chaos/ */ -module.exports = function minimumBribes(q) { - let swaps = 0; - let min = q.length; - for (let i = q.length - 1; i >= 0; i--) { - if (q[i] - i > 3) { - return 'Too chaotic'; - } - if (q[i] > i + 1) { - swaps += (q[i] - (i + 1)); - } else if (min > q[i]) { - min = q[i]; - } else if (q[i] !== min) { - swaps++; - } - } +function minimumBribes(q) { + let swaps = 0; + let min = q.length; + for (var i = q.length -1 ; i >= 0; i--) { + if (q[i] - i > 3) { + return `Too chaotic`; + } + if (q[i] > i + 1) { + swaps += (q[i] - (i + 1)); + } else { + if (min > q[i]) { + min = q[i]; + } else if (q[i] != min) { + swaps++; + } + } + } - return swaps; -}; + return swaps; +} diff --git a/src/Arrays/sock-merchant.js b/src/Arrays/sock-merchant.js index c75cf50..e865834 100644 --- a/src/Arrays/sock-merchant.js +++ b/src/Arrays/sock-merchant.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/sock-merchant */ -module.exports = function sockMerchant(n, ar) { - const tmpArr = []; - let counter = 0; - ar.map((value) => { - if (tmpArr.includes(value)) { - const index = tmpArr.indexOf(value); - if (index > -1) { - tmpArr.splice(index, 1); - } - counter++; - } else { - tmpArr.push(value); - } - return value; - }); - return counter; -}; +function sockMerchant(n, ar) { + let tmpArr = []; + let counter = 0; + ar.map(value => { + if (tmpArr.includes(value)) { + var index = tmpArr.indexOf(value); + if (index > -1) { + tmpArr.splice(index, 1); + } + counter++; + } else { + tmpArr.push(value); + } + + }) + + return counter; + +} diff --git a/src/Data Structures/cycle-detection.js b/src/Data Structures/cycle-detection.js index 46ee960..5bd280a 100644 --- a/src/Data Structures/cycle-detection.js +++ b/src/Data Structures/cycle-detection.js @@ -6,31 +6,30 @@ */ function hasCycle(head) { - if (head === null || head.next === null || head.next.next === null) return false; // edge cases - let hare = head; - let tortoise = head; - do { - hare = hare.next.next; // 'hare' moves twice per tick - tortoise = tortoise.next; // 'tortoise' moves once per tick - } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); - return hare === tortoise; + if (head === null || head.next === null || head.next.next === null) return false; // edge cases + let hare = head; + let tortoise = head; + do { + hare = hare.next.next; // 'hare' moves twice per tick + tortoise = tortoise.next; // 'tortoise' moves once per tick + } while (hare !== tortoise && hare.next !== null && hare.next.next !== null); + return hare === tortoise; } // NODE CLASS class Node { - constructor(data) { - this.data = data; - this.next = null; - } - - insert(data) { - this.next = new Node(data); - return this.next; // for chaining - } + constructor (data) { + this.data = data; + this.next = null; + } + insert (data) { + this.next = new Node(data); + return this.next; // for chaining + } } module.exports = { - hasCycle, - Node, -}; + hasCycle, + Node, +}; \ No newline at end of file diff --git a/src/Data Structures/reverse-doubly-linked-list.js b/src/Data Structures/reverse-doubly-linked-list.js index c5bae4f..04dcde3 100644 --- a/src/Data Structures/reverse-doubly-linked-list.js +++ b/src/Data Structures/reverse-doubly-linked-list.js @@ -1,3 +1,4 @@ +'use strict'; /* Title: Reverse a doubly linked list Difficulty: Easy @@ -5,49 +6,51 @@ Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem */ -class DoublyLinkedListNode { - constructor(nodeData) { - this.data = nodeData; - this.next = null; - this.prev = null; - } -} -class DoublyLinkedList { - constructor() { - this.head = null; - this.tail = null; - } - - insertNode(nodeData) { - const node = new DoublyLinkedListNode(nodeData); - - if (this.head == null) { - this.head = node; - } else { - this.tail.next = node; - node.prev = this.tail; - } - - this.tail = node; - } -} function reverse(head) { - while (head.next) { - head = head.next; - } - - const newList = new DoublyLinkedList(); - - while (head) { - newList.insertNode(head.data); - head = head.prev; - } - return newList.head; + while (head.next) { + head = head.next + } + + const newList = new DoublyLinkedList(); + + while (head) { + newList.insertNode(head.data); + head = head.prev + } + return newList.head } -module.exports = { - reverse, - DoublyLinkedList, - DoublyLinkedListNode, +class DoublyLinkedListNode { + constructor(nodeData) { + this.data = nodeData; + this.next = null; + this.prev = null; + } +}; + +class DoublyLinkedList { + constructor() { + this.head = null; + this.tail = null; + } + + insertNode(nodeData) { + let node = new DoublyLinkedListNode(nodeData); + + if (this.head == null) { + this.head = node; + } else { + this.tail.next = node; + node.prev = this.tail; + } + + this.tail = node; + } }; + +module.exports = { + reverse, + DoublyLinkedList, + DoublyLinkedListNode +} diff --git a/src/Dictionaries and Hashmaps/count-triplet.js b/src/Dictionaries and Hashmaps/count-triplet.js index 38656ad..ac8d48c 100644 --- a/src/Dictionaries and Hashmaps/count-triplet.js +++ b/src/Dictionaries and Hashmaps/count-triplet.js @@ -6,29 +6,30 @@ */ function countTriplets(arr, r) { - const second = {}; - const third = {}; - let count = 0; - for (let index = 0; index < arr.length; index++) { - const val = arr[index]; + let second = {} + let third = {} + let count = 0; + for (let index = 0; index < arr.length; index++) { - // If value found on third then add it to count - if (third[val]) { - count += third[val]; - } + const val = arr[index]; - // If value found on second , convey it to third + //If value found on third then add it to count + if(third[val]){ + count += third[val]; + } - if (second[val]) { - third[val * r] = third[val * r] + second[val] || second[val]; - } + //If value found on second , convey it to third - // add current element into second value + if(second[val]){ + third[val*r] = third[val*r] + second[val] || second[val]; + } - second[val * r] = second[val * r] + 1 || 1; - } + //add current element into second value - return count; + second[val*r] = second[val*r]+1 || 1; + } + + return count; } -console.log(countTriplets([1, 2, 2, 4], 2)); +console.log(countTriplets([1,2 ,2,4], 2)); diff --git a/src/Dictionaries and Hashmaps/custom-hashmap.js b/src/Dictionaries and Hashmaps/custom-hashmap.js index 4c05db3..c2431ec 100644 --- a/src/Dictionaries and Hashmaps/custom-hashmap.js +++ b/src/Dictionaries and Hashmaps/custom-hashmap.js @@ -5,31 +5,31 @@ Link: - */ class customHashMap { - constructor() { - this.list = []; - } + constructor() { + this.list = []; + } - get(x) { - return this.list[this.hashCode(x)]; - } + get(x) { + return this.list[this.hashCode(x)]; + } - set(x, y) { - this.list[this.hashCode(x)] = y; - } + set(x, y) { + this.list[this.hashCode(x)] = y; + } - static hashCode(str) { - let hash = 0; - if (str.length === 0) return hash; - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash &= hash; // Convert to 32bit integer - } - return hash; - } + hashCode(str) { + let hash = 0; + if (str.length == 0) return hash; + for (let i = 0; i < str.length; i++) { + let char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash = hash & hash; // Convert to 32bit integer + } + return hash; + } } -const m = customHashMap(); +let m = new customHashMap(); m.set('hello', 'world'); console.log(m.get('hello')); diff --git a/src/Dictionaries and Hashmaps/frequency-queries.js b/src/Dictionaries and Hashmaps/frequency-queries.js index 40ccb6b..c3f4d5a 100644 --- a/src/Dictionaries and Hashmaps/frequency-queries.js +++ b/src/Dictionaries and Hashmaps/frequency-queries.js @@ -6,40 +6,40 @@ */ function freqQuery(arr) { - const result = []; - const hash = {}; - const freq = []; + const result = []; + const hash = {}; + const freq = []; - for (let i = 0; i < arr.length; i += 1) { - const [action, value] = arr[i]; - const initValue = hash[value] || 0; + for (let i = 0; i < arr.length; i += 1) { + const [action, value] = arr[i]; + const initValue = hash[value] || 0; - if (action === 1) { - hash[value] = initValue + 1; - freq[initValue] = (freq[initValue] || 0) - 1; - freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; - } + if (action === 1) { + hash[value] = initValue + 1; + freq[initValue] = (freq[initValue] || 0) - 1; + freq[initValue + 1] = (freq[initValue + 1] || 0) + 1; + } - if (action === 2 && initValue > 0) { - hash[value] = initValue - 1; - freq[initValue - 1] += 1; - freq[initValue] -= 1; - } + if (action === 2 && initValue > 0) { + hash[value] = initValue - 1; + freq[initValue - 1] += 1; + freq[initValue] -= 1; + } - if (action === 3) result.push(freq[value] > 0 ? 1 : 0); - } + if (action === 3) result.push(freq[value] > 0 ? 1 : 0); + } - return result; + return result; } -const input = [ - [1, 5], - [1, 6], - [3, 2], - [1, 10], - [1, 10], - [1, 6], - [2, 5], - [3, 2], -]; +let input = [ + [1, 5], + [1, 6], + [3, 2], + [1, 10], + [1, 10], + [1, 6], + [2, 5], + [3, 2] + ]; console.log(freqQuery(input)); diff --git a/src/Dictionaries and Hashmaps/game-of-thrones.js b/src/Dictionaries and Hashmaps/game-of-thrones.js index 31e1f31..0d50f1e 100644 --- a/src/Dictionaries and Hashmaps/game-of-thrones.js +++ b/src/Dictionaries and Hashmaps/game-of-thrones.js @@ -6,12 +6,12 @@ */ function gameOfThrones(s) { - const frequencies = {}; - for (const char of s) frequencies[char] = frequencies[char] + 1 || 1; - const oddFrequencies = Object.values(frequencies).filter((frequency) => frequency % 2); - return oddFrequencies.length <= 1 ? 'YES' : 'NO'; + const frequencies = {}; + for (let char of s) frequencies[char] = frequencies[char] + 1 || 1; + let oddFrequencies = Object.values(frequencies).filter(frequency => frequency % 2); + return oddFrequencies.length <= 1 ? 'YES' : 'NO'; } -console.log(gameOfThrones('aaabbbb')); // YES -console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO -console.log(gameOfThrones('cdcdcdcdeeeef')); // YES +console.log(gameOfThrones('aaabbbb')); // YES +console.log(gameOfThrones('cdefghmnopqrstuvw')); // NO +console.log(gameOfThrones('cdcdcdcdeeeef')); // YES \ No newline at end of file diff --git a/src/Dictionaries and Hashmaps/ransom-note.js b/src/Dictionaries and Hashmaps/ransom-note.js index 2268c69..bf7003a 100644 --- a/src/Dictionaries and Hashmaps/ransom-note.js +++ b/src/Dictionaries and Hashmaps/ransom-note.js @@ -6,48 +6,51 @@ */ class ExtendedMap { - constructor() { - this.map = new Map(); - } - - get(x) { - let value = this.map.get(x); - if (value === 1) { - this.map.delete(x); - return true; - } - - return this.map.set(x, --value); - } - - set(x, y) { - if (this.map.get(x)) { - return this.map.set(x, this.map.get(x) + 1); - } - - return this.map.set(x, y); - } + + constructor(){ + this.map = new Map(); + } + + get(x) { + let value = this.map.get(x); + if (value === 1) { + this.map.delete(x); + return true; + } + + return this.map.set(x, --value); + } + + set(x, y) { + if (this.map.get(x)) { + return this.map.set(x, this.map.get(x) + 1); + } + + return this.map.set(x, y); + } } + function checkMagazine(magazine, note) { - const m = new ExtendedMap(); - for (let i = 0; i < magazine.length; i++) { - m.set(magazine[i], 1); - } + let m = new ExtendedMap() + + for (let i = 0; i < magazine.length; i++) { + m.set(magazine[i], 1) + } - for (let i = 0; i < note.length; i++) { - if (!m.get(note[i])) { - console.log('No'); - return; - } - } + for (let i = 0; i < note.length; i++) { + if (!m.get(note[i])) { + console.log('No'); + return; + }; + } - console.log('Yes'); + console.log('Yes'); } -const magazine = ['give', 'me', 'one', 'grand', 'today', 'night']; -const note = ['give', 'one', 'grand', 'today']; +let magazine = [ 'give', 'me', 'one', 'grand', 'today', 'night' ]; +let note = [ 'give', 'one', 'grand', 'today' ]; console.time('Time Taken'); checkMagazine(magazine, note); diff --git a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js index 8b655d9..138f0db 100644 --- a/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js +++ b/src/Dictionaries and Hashmaps/sherlock-and-anagrams.js @@ -5,23 +5,23 @@ Link: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ */ function sherlockAndAnagrams(s) { - let count = 0; - const strLength = s.length; // get length - for (let i = 1; i < strLength; i++) { - const found = {}; - for (let j = 0; j + i <= strLength; j++) { - let substr = s.substr(j, i); // device string into substr - substr = substr.split('').sort().join(''); // sort it - if (found[substr]) { - count += found[substr]; // count total - found[substr]++; - } else { - found[substr] = 1; - } - } - } + let count = 0; + let strLength = s.length; //get length + for (let i = 1; i < strLength; i++) { + let found = {}; + for (let j = 0; j + i <= strLength; j++) { + let substr = s.substr(j, i); //device string into substr + substr = substr.split('').sort().join(''); //sort it + if (found[substr]) { + count += found[substr]; //count total + found[substr]++; + } else { + found[substr] = 1; + } + } + } - return count; + return count; } console.log(sherlockAndAnagrams('cdcd')); diff --git a/src/Dictionaries and Hashmaps/two-strings.js b/src/Dictionaries and Hashmaps/two-strings.js index cc1845d..f9f7e3d 100644 --- a/src/Dictionaries and Hashmaps/two-strings.js +++ b/src/Dictionaries and Hashmaps/two-strings.js @@ -6,21 +6,22 @@ */ function twoStrings(s1, s2) { - const m = new Map(); - for (let i = 0; i < s1.length; i++) { - m.set(s1[i], 1); - } + m = new Map(); + for(let i=0; i { - if (grade < 38) { - return grade; - } +function gradingStudents(grades) { + let newGrades = grades.map(grade => { + if (grade < 38) { + return grade; + } - const roundRemainder = grade % 5; + let roundRemainder = grade % 5; - if (roundRemainder === 0 || roundRemainder <= 2) { - return grade; - } + if (roundRemainder === 0 || roundRemainder <= 2) { + return grade; + } - return grade + (5 - roundRemainder); - }); + return grade + (5 - roundRemainder); + }) - return newGrades; -}; + return newGrades; + +} diff --git a/src/Numbers/kangaroo.js b/src/Numbers/kangaroo.js index 90ae9da..06495a1 100644 --- a/src/Numbers/kangaroo.js +++ b/src/Numbers/kangaroo.js @@ -7,26 +7,29 @@ // Solution 1 function kangaroo(x1, v1, x2, v2) { - if ((x2 > x1 && v2 > v1) || v1 === v2) { - return 'NO'; - } + if ((x2 > x1 && v2 > v1) || v1 === v2) { + return 'NO'; + } - let x1Distance = x1; - let x2Distance = x2; + let x1Distance = x1; + let x2Distance = x2; - while (x1Distance !== x2Distance) { - x1Distance += v1; - x2Distance += v2; + while (x1Distance !== x2Distance) { + x1Distance += v1; + x2Distance += v2; - if (x1Distance > x2Distance) { - return 'NO'; - } - } + if (x1Distance > x2Distance) { + return 'NO'; + } + } + + return 'YES'; - return 'YES'; } -// Solution 2 + +//Solution 2 + /* @@ -43,12 +46,11 @@ x1 - x2 / v2 - v1 = y so we can find y with all 4 inputs if it is integer and greater than 0 then both will meet */ -function kangarooSolution2(x1, v1, x2, v2) { - if (x2 > x1 && v2 > v1) { - return 'NO'; - } +function kangaroo(x1, v1, x2, v2) { + if (x2 > x1 && v2 > v1) { + return 'NO' + } - const steps = (x1 - x2) % (v2 - v1); - return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; + let steps = (x1 - x2) % (v2 - v1); + return (steps >= 0 && Number.isInteger(steps)) ? 'YES' : 'NO'; } -module.exports = [kangaroo, kangarooSolution2]; diff --git a/src/Numbers/plus-minus.js b/src/Numbers/plus-minus.js index 164be6c..b754238 100644 --- a/src/Numbers/plus-minus.js +++ b/src/Numbers/plus-minus.js @@ -6,22 +6,22 @@ */ module.exports = function plusMinus(arr) { - const result = { - positive: 0, - negative: 0, - zero: 0, - }; + let result = { + positive: 0, + negative: 0, + zero: 0, + } - const arrLength = arr.length; - for (let index = 0; index < arrLength; index++) { - if (arr[index] === 0) { - ++result.zero; - } else if (arr[index] > 0) { - ++result.positive; - } else { - ++result.negative; - } - } + let arrLength = arr.length; + for (let index = 0; index < arrLength; index++){ + if (arr[index] === 0) { + ++result.zero; + } else if (arr[index] > 0) { + ++result.positive; + } else { + ++result.negative; + } + } - return result; -}; + return result; +} diff --git a/src/Numbers/staircase.js b/src/Numbers/staircase.js index 6a05c07..f09ff35 100644 --- a/src/Numbers/staircase.js +++ b/src/Numbers/staircase.js @@ -6,10 +6,10 @@ */ function staircase(n) { - let tmp = n; - for (let index = 0; index < n; index++) { - console.log(' '.repeat(--tmp) + '#'.repeat(index + 1)); - } + let tmp = n; + for (let index = 0; index < n; index++){ + console.log(' '.repeat(--tmp) + '#'.repeat(index + 1 )); + } } staircase(6); diff --git a/src/Sorting/bubble-sort.js b/src/Sorting/bubble-sort.js index 794c249..d6d9c81 100644 --- a/src/Sorting/bubble-sort.js +++ b/src/Sorting/bubble-sort.js @@ -6,22 +6,22 @@ */ function countSwaps(a) { - let isSorted = false; - let counter = 0; - while (!isSorted) { - isSorted = true; - for (let i = 0; i < a.length - 1; i++) { - if (a[i] > a[i + 1]) { - [a[i], a[i + 1]] = [a[i + 1], a[i]]; - counter++; - isSorted = false; - } - } - } + let isSorted = false; + let counter = 0; + while (!isSorted) { + isSorted = true; + for (let i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + [a[i], a[i + 1]] = [a[i + 1], a[i]]; + counter++; + isSorted = false; + } + } + } - console.log(`Array is sorted in ${counter} swaps.`); - console.log(`First Element: ${a[0]}`); - console.log(`Last Element: ${a[a.length - 1]}`); + console.log(`Array is sorted in ${counter} swaps.`); + console.log(`First Element: ${a[0]}`); + console.log(`Last Element: ${a[a.length -1 ]}`); } countSwaps([5, 2, 1]); diff --git a/src/Sorting/mark-and-toys.js b/src/Sorting/mark-and-toys.js index efb5755..cabb6db 100644 --- a/src/Sorting/mark-and-toys.js +++ b/src/Sorting/mark-and-toys.js @@ -6,20 +6,20 @@ */ function maximumToys(prices, balance) { - prices = prices.sort((a, b) => a - b); - let toysBought = 0; - console.log(prices); - for (let i = 0; i < prices.length; i++) { - if (balance >= prices[i]) { - toysBought++; - balance -= prices[i]; - } else { - break; - } - } - return toysBought; + prices = prices.sort((a, b) => a - b) + let toysBought = 0; + console.log(prices); + for (let i = 0; i < prices.length; i++){ + if (balance >= prices[i]) { + toysBought++; + balance -= prices[i]; + } else { + break; + } + } + return toysBought; + } -const arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, - 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; +let arr = [33324560, 77661073, 31948330, 21522343, 97176507, 5724692, 24699815, 12079402, 6479353, 28430129, 42427721, 57127004, 26256001, 29446837, 65107604, 9809008, 65846182, 8470661, 13597655, 360]; console.log(maximumToys(arr, 100000)); diff --git a/src/Sorting/mini-max-sum.js b/src/Sorting/mini-max-sum.js index 79d6224..83bde36 100644 --- a/src/Sorting/mini-max-sum.js +++ b/src/Sorting/mini-max-sum.js @@ -6,14 +6,14 @@ */ function miniMaxSum(arr) { - const sum = [0, 0]; - arr = arr.sort((a, b) => a - b); - for (let i = 0; i < 4; i++) { - sum[0] += arr[i]; - sum[1] += arr[arr.length - (i + 1)]; - } + let sum = [0, 0]; + arr = arr.sort((a, b) => { return a - b }); + for (let i = 0; i < 4; i++){ + sum[0] += arr[i]; + sum[1] += arr[arr.length - (i+1)]; + } - console.log(sum[0], sum[1]); + console.log(sum[0], sum[1]); } miniMaxSum(1, 2, 3, 4, 5); diff --git a/src/Strings/alternating-characters.js b/src/Strings/alternating-characters.js index 3fbcb1a..b02de77 100644 --- a/src/Strings/alternating-characters.js +++ b/src/Strings/alternating-characters.js @@ -6,22 +6,22 @@ */ function alternatingCharacters(string) { - let prev = ''; - let counter = 0; - for (let index = 0; index < string.length; index++) { - if (!prev) { - prev = string[index]; - continue; - } + let prev = ''; + let counter = 0; + for (let index = 0; index < string.length; index++) { + if(!prev){ + prev = string[index]; + continue; + } - if (prev === string[index]) { - counter++; - } + if(prev === string[index]){ + counter++; + } - prev = string[index]; - } + prev = string[index]; + } - return counter; + return counter; } console.log(alternatingCharacters('BBBBB')); diff --git a/src/Strings/counting-valleys.js b/src/Strings/counting-valleys.js index 79459ab..dbb44ae 100644 --- a/src/Strings/counting-valleys.js +++ b/src/Strings/counting-valleys.js @@ -5,21 +5,23 @@ Link: https://www.hackerrank.com/challenges/counting-valleys */ -module.exports = function countingValleys(n, s) { - let currentValley = 0; - let count = 0; - for (let i = 0; i < n; i++) { - if (s[i] === 'U') { - currentValley++; - } - if (s[i] === 'D') { - currentValley--; - } +function countingValleys(n, s) { + let currentValley = 0; + let count = 0; + for (let i = 0; i < n; i++) { - if (currentValley === '0' && s[i] === 'U') { - count++; - } - } + if (s[i] === 'U') { + currentValley++; + } + if (s[i] === 'D') { + currentValley--; + } - return count; -}; + if (currentValley == 0 && s[i] === 'U') { + count++; + } + } + + return count; + +} diff --git a/src/Strings/hackerrank-in-string.js b/src/Strings/hackerrank-in-string.js index 2564590..1e8ebbd 100644 --- a/src/Strings/hackerrank-in-string.js +++ b/src/Strings/hackerrank-in-string.js @@ -6,12 +6,12 @@ */ module.exports = function hackerrankInString(s) { - const mask = Array.from('hackerrank'); - for (let i = 0; i < s.length; i++) { - const currentChar = s.charAt(i); - if (mask[0] === currentChar) { - mask.shift(); - } - } - return mask.length === 0 ? 'YES' : 'NO'; + const mask = Array.from("hackerrank"); + for (let i = 0; i < s.length; i++) { + const currentChar = s.charAt(i); + if (mask[0] === currentChar) { + mask.shift(); + } + } + return mask.length === 0 ? "YES" : "NO"; }; diff --git a/src/Strings/making-anagrams.js b/src/Strings/making-anagrams.js index 864472a..4de1579 100644 --- a/src/Strings/making-anagrams.js +++ b/src/Strings/making-anagrams.js @@ -5,44 +5,46 @@ Link: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_r=internal-search */ + +function makeAnagram(string1, string2){ + string1 = count(string1); + string2 = count(string2); + return findDiff(string1, string2); +} + function count(a) { - const arr = a.split('').sort(); - const counter = {}; - arr.forEach((value) => { - if (counter[value] !== undefined) { - counter[value] += 1; - } else { - counter[value] = 1; - } - }); - - return counter; + let arr = a.split('').sort(); + let counter = {}; + arr.forEach(value => { + if (counter[value] !== undefined) { + counter[value] += 1; + } else { + counter[value] = 1; + } + }) + + return counter; } function findDiff(arr1, arr2) { - let removeCount = 0; - - for (const key in arr1) { - if (!arr2[key]) { - removeCount += arr1[key]; - } else { - removeCount += Math.abs(arr2[key] - arr1[key]); - } - } - - for (const key in arr2) { - if (!arr1[key]) { - removeCount += arr2[key]; - } - } - return removeCount; -} -function makeAnagram(string1, string2) { - string1 = count(string1); - string2 = count(string2); - return findDiff(string1, string2); + let removeCount = 0; + + for (let key in arr1) { + if (!arr2[key]) { + removeCount += arr1[key]; + } else { + removeCount += Math.abs(arr2[key] - arr1[key]); + } + } + + for (let key in arr2) { + if (!arr1[key]) { + removeCount += arr2[key]; + } + } + return removeCount; } -const a = 'fcrxzwscanmligyxyvym'; -const b = 'jxwtrhvujlmrpdoqbisbwhmgpmeoke'; -console.log(makeAnagram(a, b)); +let a = "fcrxzwscanmligyxyvym"; +let b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"; +console.log(makeAnagram(a,b )); diff --git a/src/Strings/repeated-string.js b/src/Strings/repeated-string.js index 6e71159..4497df6 100644 --- a/src/Strings/repeated-string.js +++ b/src/Strings/repeated-string.js @@ -6,11 +6,11 @@ */ module.exports = function repeatedString(s, n) { - const initialCount = s.split('a').length - 1; - const cocent = Math.floor(n / s.length); - let total = cocent * initialCount; - const remainder = n % s.length; - const remaindLetter = s.slice(0, remainder); - total += remaindLetter.split('a').length - 1; - return total; -}; + let initialCount = s.split('a').length - 1; + let cocent = Math.floor(n / s.length); + let total = cocent * initialCount; + let remainder = n % s.length; + let remaindLetter = s.slice(0, remainder); + total += remaindLetter.split('a').length - 1; + return total; +} diff --git a/src/Strings/sherlock-and-the-valid-string.js b/src/Strings/sherlock-and-the-valid-string.js index d786906..5846fcf 100644 --- a/src/Strings/sherlock-and-the-valid-string.js +++ b/src/Strings/sherlock-and-the-valid-string.js @@ -6,35 +6,36 @@ */ function isValid(string) { - const counter = {}; - - const arr = string.split('').sort(); - let smallValue = 0; - let allowedTimes = 0; - arr.forEach((element) => { - counter[element] = counter[element] === undefined ? 1 : counter[element] + 1; - }); - - for (const key in counter) { - if (smallValue === 0) { - smallValue = counter[key]; - continue; - } - - if (smallValue !== counter[key]) { - if (counter[key] === 1) { - allowedTimes += 1; - } else { - allowedTimes += Math.abs(smallValue - counter[key]); - } - } - - if (allowedTimes > 1) { - break; - } - } - - return !(allowedTimes > 1); + let counter = {}; + + let arr = string.split('').sort(); + let smallValue = 0; + let allowedTimes = 0; + arr.forEach(element => { + counter[element] = counter[element] === undefined ? 1 : counter[element]+1; + }); + + for(let key in counter){ + if(smallValue === 0){ + smallValue = counter[key]; + continue ; + } + + if(smallValue !== counter[key]){ + if(counter[key] === 1){ + allowedTimes += 1; + } else { + allowedTimes += Math.abs(smallValue - counter[key]); + } + } + + if(allowedTimes > 1){ + break; + } + } + + return allowedTimes > 1 ? false : true; } -console.log(isValid('abcdefghhgfedecba')); + +console.log(isValid("abcdefghhgfedecba")); diff --git a/src/Strings/strong-password.js b/src/Strings/strong-password.js index fa54fb6..d3fd7c0 100644 --- a/src/Strings/strong-password.js +++ b/src/Strings/strong-password.js @@ -6,21 +6,27 @@ */ module.exports = function passwordStrengthMinimumNumber(n, password) { - const STRONG_LENGTH = 6; - const missingChars = STRONG_LENGTH - n; - let score = 0; + const STRONG_LENGTH = 6; + const missingChars = STRONG_LENGTH - n; + let score = 0; - const passwordAsArray = Array.from(password); + const passwordAsArray = Array.from(password); - const hasNumber = passwordAsArray.some((char) => '0123456789'.includes(char)); - const hasLowerCase = passwordAsArray.some((char) => 'abcdefghijklmnopqrstuvwxyz'.includes(char)); - const hasUpperCase = passwordAsArray.some((char) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(char)); - const hasSpecialChar = passwordAsArray.some((char) => '!@#$%^&*()-+'.includes(char)); + const hasNumber = passwordAsArray.some(char => "0123456789".includes(char)); + const hasLowerCase = passwordAsArray.some(char => + "abcdefghijklmnopqrstuvwxyz".includes(char) + ); + const hasUpperCase = passwordAsArray.some(char => + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(char) + ); + const hasSpecialChar = passwordAsArray.some(char => + "!@#$%^&*()-+".includes(char) + ); - if (!hasNumber) score++; - if (!hasLowerCase) score++; - if (!hasUpperCase) score++; - if (!hasSpecialChar) score++; + if (!hasNumber) score++; + if (!hasLowerCase) score++; + if (!hasUpperCase) score++; + if (!hasSpecialChar) score++; - return Math.max(score, missingChars); + return Math.max(score, missingChars); }; diff --git a/src/Strings/time-conversion.js b/src/Strings/time-conversion.js index dc86243..6cabfbc 100644 --- a/src/Strings/time-conversion.js +++ b/src/Strings/time-conversion.js @@ -5,23 +5,24 @@ Link: https://www.hackerrank.com/challenges/time-conversion/ */ + module.exports = function timeConversion(time) { - const cycle = time.substring(time.length - 2, time.length); - const timeWithoutCycle = time.substring(0, time.length - 2); - const timeArr = timeWithoutCycle.split(':'); + let cycle = time.substring(time.length - 2, time.length); + let timeWithoutCycle = time.substring(0, time.length - 2); + let timeArr = timeWithoutCycle.split(':'); - if (cycle === 'AM') { - if (timeArr[0] !== '12') { - return timeWithoutCycle; - } + if (cycle === 'AM') { + if (timeArr[0] != 12) { + return timeWithoutCycle; + } - timeArr[0] = '00'; - return timeArr.join(':'); - } + timeArr[0] = '00'; + return timeArr.join(':'); + } - if (timeArr[0] !== '12') { - timeArr[0] = parseInt(timeArr[0], 10) + 12; - } + if (timeArr[0] != 12) { + timeArr[0] = parseInt(timeArr[0]) + 12; + } - return timeArr.join(':'); -}; + return timeArr.join(':') +} diff --git a/test/Arrays/birthday-cake-candles.test.js b/test/Arrays/birthday-cake-candles.test.js index 506cc68..5d43aba 100644 --- a/test/Arrays/birthday-cake-candles.test.js +++ b/test/Arrays/birthday-cake-candles.test.js @@ -1,28 +1,28 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const birthdayCakeCandles = require('../../src/Arrays/birthday-cake-candles'); +const birthdayCakeCandles = require("../../src/Arrays/birthday-cake-candles"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Birthday Cake Candles', () => { - it('returns 0 for empty array', () => { - expect(birthdayCakeCandles([])).to.equal(0); - }); +describe("Birthday Cake Candles", () => { + it("returns 0 for empty array", () => { + expect(birthdayCakeCandles([])).to.equal(0); + }); - it('returns 1 if there is only one candle', () => { - expect(birthdayCakeCandles([1])).to.equal(1); - expect(birthdayCakeCandles([2])).to.equal(1); - expect(birthdayCakeCandles([3])).to.equal(1); - }); + it("returns 1 if there is only one candle", () => { + expect(birthdayCakeCandles([1])).to.equal(1); + expect(birthdayCakeCandles([2])).to.equal(1); + expect(birthdayCakeCandles([3])).to.equal(1); + }); - it('returns 2 if there are two candles with the same height', () => { - expect(birthdayCakeCandles([1, 1])).to.equal(2); - expect(birthdayCakeCandles([2, 2])).to.equal(2); - expect(birthdayCakeCandles([3, 3])).to.equal(2); - }); + it("returns 2 if there are two candles with the same height", () => { + expect(birthdayCakeCandles([1, 1])).to.equal(2); + expect(birthdayCakeCandles([2, 2])).to.equal(2); + expect(birthdayCakeCandles([3, 3])).to.equal(2); + }); - it('returns correct amount for array with different sized candles', () => { - expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); - expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); - expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); - expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); - }); + it("returns correct amount for array with different sized candles", () => { + expect(birthdayCakeCandles([3, 2, 1, 3])).to.equal(2); + expect(birthdayCakeCandles([3, 2, 1, 3, 4, 5, 4])).to.equal(1); + expect(birthdayCakeCandles([3, 2, 1, 1, 2, 2, 4, 4, 4])).to.equal(3); + expect(birthdayCakeCandles([3, 2, 1])).to.equal(1); + }); }); diff --git a/test/Arrays/left-rotation.test.js b/test/Arrays/left-rotation.test.js index 0965ab2..2a4e66a 100644 --- a/test/Arrays/left-rotation.test.js +++ b/test/Arrays/left-rotation.test.js @@ -1,20 +1,22 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const leftRotation = require('../../src/Arrays/left-rotation'); +const leftRotation = require('../../src/Arrays/left-rotation') +const { describe, it } = require('mocha') +const { expect } = require('chai') describe('Left Rotation', () => { - it('should work for any empty array', () => { - expect(leftRotation([], 10)).to.deep.equal([]); - }); - it('should work for a 1 element array', () => { - const original = [1]; - expect(leftRotation(original, 10)).to.deep.equal(original); - }); + it('should work for any empty array', () => { + expect(leftRotation([], 10)).to.deep.equal([]) + }) - it('should work for multiple elements', () => { - const original = 'ABCDEF'.split(''); - const expected = 'DEFABC'.split(''); - expect(leftRotation(original, 3)).to.deep.equal(expected); - }); -}); + it('should work for a 1 element array', () => { + const original = [1] + expect(leftRotation(original, 10)).to.deep.equal(original) + }) + + it('should work for multiple elements', () => { + const original = "ABCDEF".split('') + const expected = "DEFABC".split('') + expect(leftRotation(original, 3)).to.deep.equal(expected) + }) + +}) diff --git a/test/Data Structures/cycle-detection.test.js b/test/Data Structures/cycle-detection.test.js index 24bbb2e..32fdcb7 100644 --- a/test/Data Structures/cycle-detection.test.js +++ b/test/Data Structures/cycle-detection.test.js @@ -1,54 +1,54 @@ +const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); const { describe, it } = require('mocha'); const { expect } = require('chai'); -const { hasCycle, Node } = require('../../src/Data Structures/cycle-detection'); describe('Cycle Detection', () => { - it('should detect a cycle in a regular linked list', () => { - const test1 = new Node(1); - const tail1 = test1.insert(2) // tail1 === Node #8 - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - const connection1 = test1.next.next.next; // connection1 === Node #4 - tail1.next = connection1; - expect(hasCycle(test1)).to.equal(true); - }); + it('should detect a cycle in a regular linked list', () => { + const test1 = new Node(1); + const tail1 = test1.insert(2) // tail1 === Node #8 + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + const connection1 = test1.next.next.next; // connection1 === Node #4 + tail1.next = connection1; + expect(hasCycle(test1)).to.equal(true); + }); - it('should return false when the end of the list points to null', () => { - const test2 = new Node(1); - test2.insert(2) - .insert(3) - .insert(4) - .insert(5) - .insert(6) - .insert(7) - .insert(8); - expect(hasCycle(test2)).to.equal(false); - }); + it('should return false when the end of the list points to null', () => { + const test2 = new Node(1); + test2.insert(2) + .insert(3) + .insert(4) + .insert(5) + .insert(6) + .insert(7) + .insert(8); + expect(hasCycle(test2)).to.equal(false); + }); - it('should return false when head is null instead of a node', () => { - const test3 = null; - expect(hasCycle(test3)).to.equal(false); - }); + it('should return false when head is null instead of a node', () => { + const test3 = null; + expect(hasCycle(test3)).to.equal(false); + }); - it('should return false when the linked list only has one node that points to null', () => { - const test4 = new Node(1); - expect(hasCycle(test4)).to.equal(false); - }); + it('should return false when the linked list only has one node that points to null', () => { + const test4 = new Node(1); + expect(hasCycle(test4)).to.equal(false); + }); - it('should return false when the linked list only has two nodes', () => { - const test5 = new Node(1); - test5.insert(2); - expect(hasCycle(test5)).to.equal(false); - }); + it('should return false when the linked list only has two nodes', () => { + const test5 = new Node(1); + test5.insert(2); + expect(hasCycle(test5)).to.equal(false); + }); - it('should return false when the linked list only has two nodes but the tail links to head', () => { - const test6 = new Node(1); - const tail6 = test6.insert(2); // tail6 === Node #2 - tail6.next = test6; - expect(hasCycle(test6)).to.equal(true); - }); -}); + it('should return false when the linked list only has two nodes but the tail links to head', () => { + const test6 = new Node(1); + const tail6 = test6.insert(2); // tail6 === Node #2 + tail6.next = test6; + expect(hasCycle(test6)).to.equal(true); + }); +}) diff --git a/test/Data Structures/reverse-doubly-linked-list.test.js b/test/Data Structures/reverse-doubly-linked-list.test.js index 7545ba3..4acc443 100644 --- a/test/Data Structures/reverse-doubly-linked-list.test.js +++ b/test/Data Structures/reverse-doubly-linked-list.test.js @@ -1,28 +1,29 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); const { reverse, DoublyLinkedListNode, DoublyLinkedList } = require('../../src/Data Structures/reverse-doubly-linked-list'); +const { describe, it } = require('mocha') +const { expect } = require('chai') + describe('Reverse Doubly Linked List', () => { - it('should reverse an empty list', () => { - const node = new DoublyLinkedListNode(1); - expect(reverse(node)).to.deep.equal(node); - }); + it('should reverse an empty list', () => { + let node = new DoublyLinkedListNode(1) + expect(reverse(node)).to.deep.equal(node) + }) - it('should reverse a chain of linked nodes', () => { - const list = new DoublyLinkedList(); - list.insertNode(1); - list.insertNode(2); - list.insertNode(3); - list.insertNode(4); - list.insertNode(5); + it('should reverse a chain of linked nodes', () => { + let list = new DoublyLinkedList(); + list.insertNode(1) + list.insertNode(2) + list.insertNode(3) + list.insertNode(4) + list.insertNode(5) - const reversedList = new DoublyLinkedList(); - reversedList.insertNode(5); - reversedList.insertNode(4); - reversedList.insertNode(3); - reversedList.insertNode(2); - reversedList.insertNode(1); + let reversedList = new DoublyLinkedList(); + reversedList.insertNode(5) + reversedList.insertNode(4) + reversedList.insertNode(3) + reversedList.insertNode(2) + reversedList.insertNode(1) - expect(reverse(list.head)).to.deep.equal(reversedList.head); - }); -}); + expect(reverse(list.head)).to.deep.equal(reversedList.head) + }) +}) \ No newline at end of file diff --git a/test/Numbers/plus-minus.test.js b/test/Numbers/plus-minus.test.js index 86cc971..7fa3ced 100644 --- a/test/Numbers/plus-minus.test.js +++ b/test/Numbers/plus-minus.test.js @@ -1,17 +1,17 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const plusMinus = require('../../src/Numbers/plus-minus'); +const plusMinus = require('../../src/Numbers/plus-minus') +const { describe, it } = require('mocha') +const { expect } = require('chai') describe('Plus Minus Problem', () => { - it('It should Return 2 Positive 2 Negative and 1 Zero', () => { - expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({ positive: 2, negative: 2, zero: 1 }); - }); + it('It should Return 2 Positive 2 Negative and 1 Zero', () => { + expect(plusMinus([1, 1, -1, -1, 0])).to.deep.equal({positive: 2, negative: 2, zero: 1 }); + }); - it('It should Return 5 Positive', () => { - expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({ positive: 5, negative: 0, zero: 0 }); - }); + it('It should Return 5 Positive', () => { + expect(plusMinus([1, 1, 1, 5, 6])).to.deep.equal({positive: 5, negative: 0, zero: 0 }); + }); - it('It should Return 5 Negative', () => { - expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({ positive: 0, negative: 5, zero: 0 }); - }); -}); + it('It should Return 5 Negative', () => { + expect(plusMinus([-1, -1, -1, -5, -6])).to.deep.equal({positive: 0, negative: 5, zero: 0 }); + }); +}) diff --git a/test/Strings/hackerrank-in-string.test.js b/test/Strings/hackerrank-in-string.test.js index fdbd886..349627c 100644 --- a/test/Strings/hackerrank-in-string.test.js +++ b/test/Strings/hackerrank-in-string.test.js @@ -1,24 +1,28 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const hackerrankInString = require('../../src/Strings/hackerrank-in-string'); +const hackerrankInString = require("../../src/Strings/hackerrank-in-string"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('HackerRank in a String', () => { - it('should return NO for any empty string', () => { - expect(hackerrankInString('')).to.equal('NO'); - }); +describe("HackerRank in a String", () => { + it("should return NO for any empty string", () => { + expect(hackerrankInString("")).to.equal("NO"); + }); - it('should return YES for an exact match', () => { - expect(hackerrankInString('hackerrank')).to.equal('YES'); - }); + it("should return YES for an exact match", () => { + expect(hackerrankInString("hackerrank")).to.equal("YES"); + }); - describe('should return YES inputs containing hackerrank', () => { - it('hereiamstackerrank', () => expect(hackerrankInString('hereiamstackerrank')).to.equal('YES')); - it('hhaacckkekraraannk', () => expect(hackerrankInString('hhaacckkekraraannk')).to.equal('YES')); - }); - describe("should return NO for inputs that don't contain hackerrank", () => { - it('hackerworld', () => expect(hackerrankInString('hackerworld')).to.equal('NO')); - it('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt', () => expect( - hackerrankInString('rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt'), - ).to.equal('NO')); - }); + describe("should return YES inputs containing hackerrank", () => { + it("hereiamstackerrank", () => + expect(hackerrankInString("hereiamstackerrank")).to.equal("YES")); + it("hhaacckkekraraannk", () => + expect(hackerrankInString("hhaacckkekraraannk")).to.equal("YES")); + }); + describe("should return NO for inputs that don't contain hackerrank", () => { + it("hackerworld", () => + expect(hackerrankInString("hackerworld")).to.equal("NO")); + it("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt", () => + expect( + hackerrankInString("rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt") + ).to.equal("NO")); + }); }); diff --git a/test/Strings/repeated-string.test.js b/test/Strings/repeated-string.test.js index 0dd8a47..7003391 100644 --- a/test/Strings/repeated-string.test.js +++ b/test/Strings/repeated-string.test.js @@ -1,25 +1,25 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const repeatedString = require('../../src/Strings/repeated-string'); +const repeatedString = require("../../src/Strings/repeated-string"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Repeated String', () => { - it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { - expect(repeatedString('aba', 10)).to.eq(7); - }); +describe("Repeated String", () => { + it("should return 7 with input string 'aba' and a string length of 10 to search in", () => { + expect(repeatedString("aba", 10)).to.eq(7); + }); - it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { - expect(repeatedString('aaaaaa', 1)).to.eq(1); - }); + it("should return 1 with input string 'aaaaaa' and a string length of 1 to search in", () => { + expect(repeatedString("aaaaaa", 1)).to.eq(1); + }); - it("should return n if input string is 'a'", () => { - expect(repeatedString('a', 100000)).to.eq(100000); - expect(repeatedString('a', 300)).to.eq(300); - expect(repeatedString('a', 5)).to.eq(5); - }); + it("should return n if input string is 'a'", () => { + expect(repeatedString("a", 100000)).to.eq(100000); + expect(repeatedString("a", 300)).to.eq(300); + expect(repeatedString("a", 5)).to.eq(5); + }); - it("should return 0 if the input string does not contain 'a'", () => { - expect(repeatedString('test', 20)).to.eq(0); - expect(repeatedString('bbbb', 7)).to.eq(0); - expect(repeatedString('cdcdcd', 5)).to.eq(0); - }); + it("should return 0 if the input string does not contain 'a'", () => { + expect(repeatedString("test", 20)).to.eq(0); + expect(repeatedString("bbbb", 7)).to.eq(0); + expect(repeatedString("cdcdcd", 5)).to.eq(0); + }); }); diff --git a/test/Strings/strong-password.test.js b/test/Strings/strong-password.test.js index 4e70cfc..f9fec61 100644 --- a/test/Strings/strong-password.test.js +++ b/test/Strings/strong-password.test.js @@ -1,19 +1,26 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const passwordStrengthMinimumNumber = require('../../src/Strings/strong-password'); +const passwordStrengthMinimumNumber = require("../../src/Strings/strong-password"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Strong Password', () => { - it('returns 6 for empty string', () => expect(passwordStrengthMinimumNumber(0, '')).to.equal(6)); +describe("Strong Password", () => { + it("returns 6 for empty string", () => + expect(passwordStrengthMinimumNumber(0, "")).to.equal(6)); - it('returns 3 with password length of 3', () => expect(passwordStrengthMinimumNumber(3, 'Ab1')).to.equal(3)); + it("returns 3 with password length of 3", () => + expect(passwordStrengthMinimumNumber(3, "Ab1")).to.equal(3)); - it('returns 3 with missing special character, number and uppercase letter', () => expect(passwordStrengthMinimumNumber(3, 'longenough')).to.equal(3)); + it("returns 3 with missing special character, number and uppercase letter", () => + expect(passwordStrengthMinimumNumber(3, "longenough")).to.equal(3)); - it('returns 1 with missing number', () => expect(passwordStrengthMinimumNumber(11, '#HackerRank')).to.equal(1)); + it("returns 1 with missing number", () => + expect(passwordStrengthMinimumNumber(11, "#HackerRank")).to.equal(1)); - it('returns 1 with missing special character', () => expect(passwordStrengthMinimumNumber(11, '1HackerRank')).to.equal(1)); + it("returns 1 with missing special character", () => + expect(passwordStrengthMinimumNumber(11, "1HackerRank")).to.equal(1)); - it('returns 1 with missing uppercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1hackerrank')).to.equal(1)); + it("returns 1 with missing uppercase letter", () => + expect(passwordStrengthMinimumNumber(12, "#1hackerrank")).to.equal(1)); - it('returns 1 with missing lowercase letter', () => expect(passwordStrengthMinimumNumber(12, '#1HACKERRANK')).to.equal(1)); + it("returns 1 with missing lowercase letter", () => + expect(passwordStrengthMinimumNumber(12, "#1HACKERRANK")).to.equal(1)); }); diff --git a/test/Strings/time-conversion.test.js b/test/Strings/time-conversion.test.js index 5e940bc..16ba822 100644 --- a/test/Strings/time-conversion.test.js +++ b/test/Strings/time-conversion.test.js @@ -1,21 +1,21 @@ -const { describe, it } = require('mocha'); -const { expect } = require('chai'); -const timeConversion = require('../../src/Strings/time-conversion'); +const timeConversion = require("../../src/Strings/time-conversion"); +const { describe, it } = require("mocha"); +const { expect } = require("chai"); -describe('Time Conversion', () => { - it('should convert midnight', () => { - expect(timeConversion('12:00:00AM')).to.eq('00:00:00'); - }); +describe("Time Conversion", () => { + it("should convert midnight", () => { + expect(timeConversion("12:00:00AM")).to.eq("00:00:00") + }); - it('should convert noon', () => { - expect(timeConversion('12:00:00PM')).to.eq('12:00:00'); - }); + it("should convert noon", () => { + expect(timeConversion("12:00:00PM")).to.eq("12:00:00") + }); - it('should convert an AM time', () => { - expect(timeConversion('07:05:45AM')).to.eq('07:05:45'); - }); + it("should convert an AM time", () => { + expect(timeConversion("07:05:45AM")).to.eq("07:05:45") + }); - it('should convert a PM time', () => { - expect(timeConversion('07:05:45PM')).to.eq('19:05:45'); - }); -}); + it("should convert a PM time", () => { + expect(timeConversion("07:05:45PM")).to.eq("19:05:45") + }); +}); \ No newline at end of file