├── BinarySearch_recursion_Array.js ├── Check If It Is a Straight Line.js ├── Find the Town Judge.js ├── First Bad Version.js ├── First Unique Character in a String.js ├── Implement Trie (Prefix Tree).js ├── Jewels and Stones.js ├── Majority Element.js ├── Number Complement.js ├── Pollyfill-Array-Flat.js ├── Publisher-Subscriber-designPattern.js ├── README.md ├── Ransom Note.js ├── React_StarRating.jsx ├── React_carousel.jsx ├── Remove K Digits.js ├── Single Element in a Sorted Array.js ├── Singleton_design-patter.js ├── Sorting_with_Recursion.js ├── SystemDesign_NewsFeed.js ├── Valid_Perfect_Square.js ├── currying.js ├── inheritance_functional_and_class.js ├── interchange-key-value.js ├── minLengthUnsortedArray.js ├── overlapping_elements.js ├── pollyfill-Promise.js ├── polyfill_myBind.js ├── reduce-pollyfill.js ├── remove_duplicate_objects_in_Array.js ├── tekn_ProblemSolvingRound.js ├── useWindowSize_customHook.js └── vmware_remove_charBeforeHash.js /BinarySearch_recursion_Array.js: -------------------------------------------------------------------------------- 1 | const inputArr = [1, 4, 5, 7, 9]; 2 | 3 | const search = function(arr, target, start = 0, end = arr.length) { 4 | 5 | if (start > end) { 6 | return -1 7 | } 8 | 9 | const m = start + Math.floor((end - start) / 2); 10 | 11 | if (target === arr[m]) { 12 | return 'the answer is: ' + m; 13 | } else if (target > arr[m]) { 14 | start = m + 1; 15 | return search(arr, target, start, end); 16 | 17 | } 18 | end = m - 1; 19 | return search(arr, target, start, end); 20 | 21 | } 22 | 23 | console.log(search(inputArr, 7)) //"the answer is: 3" 24 | -------------------------------------------------------------------------------- /Check If It Is a Straight Line.js: -------------------------------------------------------------------------------- 1 | // ===================== Problem Statement ================================================================= 2 | 3 | /* 4 | 5 | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. 6 | 7 | Example 1: 8 | 9 | Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 10 | Output: true 11 | Example 2: 12 | 13 | Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 14 | Output: false 15 | 16 | Constraints: 17 | 2 <= coordinates.length <= 1000 18 | coordinates[i].length == 2 19 | -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 20 | coordinates contains no duplicate point. 21 | 22 | */ 23 | 24 | 25 | 26 | 27 | //================================================= Solution ================================================= 28 | 29 | 30 | 31 | /** 32 | * @param {number[][]} coordinates 33 | * @return {boolean} 34 | */ 35 | var checkStraightLine = function(coordinates) { 36 | let totalPoints = coordinates.length; 37 | if(totalPoints === 2){ 38 | return true 39 | } 40 | let firstPoints = coordinates[0]; 41 | let secondPoints = coordinates[totalPoints-1]; 42 | let x1 = firstPoints[0]; 43 | let y1 = firstPoints[1]; 44 | let x2 = secondPoints[0]; 45 | let y2 = secondPoints[1]; 46 | let slope = (y2-y1)/(x2-x1) 47 | 48 | if (coordinates.find( point => point[1] - y1 !== (slope)*(point[0] - x1))){ 49 | return false 50 | } 51 | 52 | return true 53 | }; 54 | -------------------------------------------------------------------------------- /Find the Town Judge.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | 4 | 5 | /* In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 6 | 7 | If the town judge exists, then: 8 | 9 | The town judge trusts nobody. 10 | Everybody (except for the town judge) trusts the town judge. 11 | There is exactly one person that satisfies properties 1 and 2. 12 | You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 13 | 14 | If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: N = 2, trust = [[1,2]] 21 | Output: 2 22 | Example 2: 23 | 24 | Input: N = 3, trust = [[1,3],[2,3]] 25 | Output: 3 26 | Example 3: 27 | 28 | Input: N = 3, trust = [[1,3],[2,3],[3,1]] 29 | Output: -1 30 | Example 4: 31 | 32 | Input: N = 3, trust = [[1,2],[2,3]] 33 | Output: -1 34 | Example 5: 35 | 36 | Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] 37 | Output: 3 38 | 39 | 40 | Note: 41 | 42 | 1 <= N <= 1000 43 | trust.length <= 10000 44 | trust[i] are all different 45 | trust[i][0] != trust[i][1] 46 | 1 <= trust[i][0], trust[i][1] <= N 47 | */ 48 | 49 | 50 | 51 | 52 | //================================================= Solution ================================================= 53 | 54 | 55 | 56 | 57 | /** 58 | * @param {number} N 59 | * @param {number[][]} trust 60 | * @return {number} 61 | */ 62 | var findJudge = function(N, trust) { 63 | let right= []; 64 | let left= []; 65 | trustLength = trust.length 66 | if(trustLength === 0){ 67 | return 1; 68 | } 69 | 70 | if(trustLength === 1){ 71 | return trust[0][1]; 72 | } 73 | for (let k = 0; k < trustLength; k++){ 74 | 75 | left.push(trust[k][0]); 76 | right.push(trust[k][1]); 77 | 78 | } 79 | right = right.filter( item => { 80 | return !left.includes(item); 81 | }) 82 | 83 | if(right.length === N - 1){ 84 | return right[0]; 85 | } 86 | 87 | return -1; 88 | 89 | }; 90 | 91 | -------------------------------------------------------------------------------- /First Bad Version.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | 4 | 5 | /* You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 6 | 7 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 8 | 9 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 10 | 11 | Example: 12 | 13 | Given n = 5, and version = 4 is the first bad version. 14 | 15 | call isBadVersion(3) -> false 16 | call isBadVersion(5) -> true 17 | call isBadVersion(4) -> true 18 | 19 | Then 4 is the first bad version. 20 | */ 21 | 22 | 23 | 24 | 25 | //================================================= Solution ================================================= 26 | 27 | 28 | 29 | /** 30 | * Definition for isBadVersion() 31 | * 32 | * @param {integer} version number 33 | * @return {boolean} whether the version is bad 34 | * isBadVersion = function(version) { 35 | * ... 36 | * }; 37 | */ 38 | 39 | /** 40 | * @param {function} isBadVersion() 41 | * @return {function} 42 | */ 43 | 44 | 45 | 46 | var solution = function(isBadVersion) { 47 | /** 48 | * @param {integer} n Total versions 49 | * @return {integer} The first bad version 50 | */ 51 | 52 | return function(n) { 53 | 54 | let first = 0; 55 | let last = n; 56 | let middle = 0; 57 | while(first < last){ 58 | middle = Math.floor( (first + last) /2 ); 59 | if(isBadVersion(middle)){ 60 | last = middle; 61 | } else{ 62 | first = middle +1; 63 | } 64 | } 65 | return last; 66 | }; 67 | }; -------------------------------------------------------------------------------- /First Unique Character in a String.js: -------------------------------------------------------------------------------- 1 | // ===================== Problem Statement ================================================================= 2 | 3 | /* 4 | 5 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 6 | 7 | Examples: 8 | 9 | s = "leetcode" 10 | return 0. 11 | 12 | s = "loveleetcode", 13 | return 2. 14 | Note: You may assume the string contain only lowercase letters. 15 | 16 | */ 17 | 18 | 19 | 20 | 21 | //================================================= Solution ================================================= 22 | 23 | 24 | 25 | /** 26 | * @param {string} s 27 | * @return {number} 28 | */ 29 | var firstUniqChar = function(s) { 30 | for (let i = 0; i< s.length; i++){ 31 | if (s.indexOf(s[i]) === s.lastIndexOf(s[i])){ 32 | return i; 33 | } 34 | } 35 | return -1; 36 | }; -------------------------------------------------------------------------------- /Implement Trie (Prefix Tree).js: -------------------------------------------------------------------------------- 1 | // ===================== Problem Statement ================================================================= 2 | 3 | /* 4 | Implement a trie with insert, search, and startsWith methods. 5 | 6 | Example: 7 | 8 | Trie trie = new Trie(); 9 | 10 | trie.insert("apple"); 11 | trie.search("apple"); // returns true 12 | trie.search("app"); // returns false 13 | trie.startsWith("app"); // returns true 14 | trie.insert("app"); 15 | trie.search("app"); // returns true 16 | Note: 17 | 18 | You may assume that all inputs are consist of lowercase letters a-z. 19 | All inputs are guaranteed to be non-empty strings. 20 | 21 | */ 22 | 23 | 24 | 25 | 26 | //================================================= Solution ================================================= 27 | 28 | 29 | 30 | /** 31 | * Initialize your data structure here. 32 | */ 33 | var Trie = function() { 34 | this.data = {}; 35 | }; 36 | 37 | /** 38 | * Inserts a word into the trie. 39 | * @param {string} word 40 | * @return {void} 41 | */ 42 | Trie.prototype.insert = function(word) { 43 | this.data[word] = word; 44 | }; 45 | 46 | /** 47 | * Returns if the word is in the trie. 48 | * @param {string} word 49 | * @return {boolean} 50 | */ 51 | Trie.prototype.search = function(word) { 52 | if(this.data[word]){ 53 | return true; 54 | } 55 | return false; 56 | }; 57 | 58 | /** 59 | * Returns if there is any word in the trie that starts with the given prefix. 60 | * @param {string} prefix 61 | * @return {boolean} 62 | */ 63 | Trie.prototype.startsWith = function(prefix) { 64 | 65 | for(let key in this.data){ 66 | if(key.startsWith(prefix)){ 67 | return true 68 | } 69 | } 70 | return false; 71 | }; 72 | 73 | /** 74 | * Your Trie object will be instantiated and called as such: 75 | * var obj = new Trie() 76 | * obj.insert(word) 77 | * var param_2 = obj.search(word) 78 | * var param_3 = obj.startsWith(prefix) 79 | */ 80 | 81 | 82 | -------------------------------------------------------------------------------- /Jewels and Stones.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | /* 4 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 5 | 6 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 7 | 8 | Example 1: 9 | 10 | Input: J = "aA", S = "aAAbbbb" 11 | Output: 3 12 | Example 2: 13 | 14 | Input: J = "z", S = "ZZ" 15 | Output: 0 16 | Note: 17 | 18 | S and J will consist of letters and have length at most 50. 19 | The characters in J are distinct. 20 | */ 21 | 22 | 23 | 24 | 25 | 26 | //================================================= Solution ================================================= 27 | 28 | 29 | 30 | 31 | /** 32 | * @param {string} J 33 | * @param {string} S 34 | * @return {number} 35 | */ 36 | 37 | 38 | 39 | var numJewelsInStones = function(J, S) { 40 | arrayJ = J.split(''); 41 | arrayS = S.split(''); 42 | let result = []; 43 | for (let i = 0; i< arrayJ.length; i++ ){ 44 | 45 | for (let k = 0; k< arrayS.length; k++ ){ 46 | 47 | if(arrayS[k] === arrayJ[i]){ 48 | result.push(arrayS[k]) 49 | arrayS.splice(k,1) 50 | --k 51 | } 52 | } 53 | } 54 | return result.length 55 | }; -------------------------------------------------------------------------------- /Majority Element.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | 4 | /* 5 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 6 | 7 | You may assume that the array is non-empty and the majority element always exist in the array. 8 | 9 | Example 1: 10 | 11 | Input: [3,2,3] 12 | Output: 3 13 | Example 2: 14 | 15 | Input: [2,2,1,1,1,2,2] 16 | Output: 2 17 | 18 | */ 19 | 20 | 21 | 22 | //================================================= Solution ================================================= 23 | 24 | 25 | 26 | /** 27 | * @param {number[]} nums 28 | * @return {number} 29 | */ 30 | var majorityElement = function(nums) { 31 | let mappingObj ={}; 32 | let arrayLength = nums.length; 33 | let majorityLength = Math.floor(arrayLength/2) 34 | for(let i = 0; i < arrayLength; i++){ 35 | if(mappingObj[nums[i]]){ 36 | mappingObj[nums[i]]++; 37 | } else{ 38 | mappingObj[nums[i]] = 1; 39 | } 40 | 41 | if(mappingObj[nums[i]] > majorityLength){ 42 | return nums[i] 43 | } 44 | } 45 | return Object.keys(mappingObj).find(item => mappingObj[item] > majorityLength); 46 | }; 47 | -------------------------------------------------------------------------------- /Number Complement.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | 4 | /* 5 | 6 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: 5 13 | Output: 2 14 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 15 | 16 | 17 | Example 2: 18 | 19 | Input: 1 20 | Output: 0 21 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 22 | 23 | 24 | Note: 25 | 26 | The given integer is guaranteed to fit within the range of a 32-bit signed integer. 27 | You could assume no leading zero bit in the integer’s binary representation. 28 | 29 | */ 30 | 31 | 32 | //================================================= Solution ================================================= 33 | 34 | 35 | /** 36 | * @param {number} num 37 | * @return {number} 38 | */ 39 | var findComplement = function(num) { 40 | 41 | let complementArray =[]; 42 | let remainder, complement, power = 0; 43 | while(num >= 1){ 44 | remainder = num % 2; 45 | num = Math.floor(num / 2); 46 | complement = remainder ? 0 : 1; 47 | complementArray.push(complement); 48 | } 49 | return complementArray.reduce((prev, current ) => prev + current* Math.pow(2, power++) ,0); 50 | 51 | }; -------------------------------------------------------------------------------- /Pollyfill-Array-Flat.js: -------------------------------------------------------------------------------- 1 | const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; 2 | const flatten = (arr, depth, result = []) => { 3 | 4 | for (let i = 0; i < arr.length; i++) { 5 | if (Array.isArray(arr[i]) && depth >= 1) { 6 | depth--; 7 | flatten(arr[i], depth, result) 8 | 9 | } else { 10 | result.push(arr[i]) 11 | } 12 | } 13 | return result; 14 | } 15 | 16 | console.log(flatten(arr4, 6)); 17 | -------------------------------------------------------------------------------- /Publisher-Subscriber-designPattern.js: -------------------------------------------------------------------------------- 1 | const PubSub = function() { 2 | 3 | const Subscriber = {}; 4 | 5 | const subscribe = function(eventName, cb) { 6 | 7 | if (!Array.isArray(Subscriber[eventName])) { 8 | Subscriber[eventName] = [] 9 | } 10 | Subscriber[eventName].push(cb); //subsciber subscribes to events and store callbacks in array. 11 | return { 12 | unsubscribe() { //unsubscribe 13 | Subscriber[eventName] = Subscriber[eventName].filter(item => item != cb); 14 | } 15 | } 16 | } 17 | 18 | const publish = function(eventName, data) { 19 | 20 | if (!Array.isArray(Subscriber[eventName])) { 21 | return 22 | } 23 | Subscriber[eventName].forEach(event => event(data)); //publish calls all the cb subscribed to that event. 24 | } 25 | 26 | return { 27 | publish, 28 | subscribe 29 | } 30 | } 31 | 32 | 33 | const pubsub = PubSub(); 34 | 35 | 36 | const result = pubsub.subscribe('consoleData', function(data) { 37 | console.log("Subscribed", data); 38 | }) 39 | 40 | const result2 = pubsub.subscribe('consoleData', function(data) { 41 | console.log("Subscribed 2", data); 42 | }) 43 | 44 | 45 | 46 | pubsub.publish('consoleData', 'This is the data published'); 47 | result.unsubscribe() 48 | result2.unsubscribe() 49 | pubsub.publish('consoleData', 'This is the data published 2'); // this data is not consoled as we have unsubscribed both the results. 50 | 51 | 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScriptCoding 2 | The repo contains JavaScript coding questions with their solutions. 3 | 4 | I will be adding questions as and when I encounter them and solve them. 5 | 6 | These questions can be helpful for anyone looking to hone their JavaScript skill. 7 | 8 | This repository will also be helpful for those looking for an opportunity in a Product based company as a JavaScript/UI developer. Majority of these companies conduct a coding round with coding difficulty level similar to the questions solved here. 9 | 10 | Also, I would appreciate if someone comes up with a better solution to the answers that I have posted, then he/she can go ahead and raise a PR with proper explanation as to why the solution is better. It would help me document the solutions better for others. 11 | -------------------------------------------------------------------------------- /Ransom Note.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | /* 4 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 5 | 6 | Each letter in the magazine string can only be used once in your ransom note. 7 | 8 | Note: 9 | You may assume that both strings contain only lowercase letters. 10 | 11 | canConstruct("a", "b") -> false 12 | canConstruct("aa", "ab") -> false 13 | canConstruct("aa", "aab") -> true 14 | */ 15 | 16 | 17 | 18 | 19 | 20 | //================================================= Solution ================================================= 21 | 22 | 23 | 24 | 25 | /** 26 | * @param {string} ransomNote 27 | * @param {string} magazine 28 | * @return {boolean} 29 | */ 30 | 31 | 32 | var canConstruct = function(ransomNote, magazine) { 33 | 34 | if(magazine.includes(ransomNote)){ 35 | return true 36 | }; 37 | let count = 0; 38 | let magazineArray = magazine.split('') 39 | 40 | for (let i = 0; i < ransomNote.length; i++ ){ 41 | let index = magazineArray.indexOf(ransomNote[i]) 42 | if (index!= -1){ 43 | delete magazineArray[index] 44 | count++ 45 | } 46 | } 47 | if(count === ransomNote.length ){ 48 | return true 49 | } else{ 50 | return false 51 | } 52 | }; -------------------------------------------------------------------------------- /React_StarRating.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import "./styles.css"; 3 | export default function App() { 4 | const [starIndex, setStarIndex] = useState(0); 5 | const Star = function ({ handleClick, className, index, starIndex }) { 6 | return ( 7 |
= index ? "star highlight" : "star"}>
8 | ); 9 | }; 10 | const numberOfStars = new Array(1, 2, 3, 4, 5); 11 | 12 | const handleClick = function (index) { 13 | setStarIndex(index); 14 | console.log(starIndex); 15 | }; 16 | return ( 17 |
18 |

Hello CodeSandbox

19 |
20 | {numberOfStars.map((item, index) => ( 21 |
handleClick(index)}> 22 | 23 |
24 | ))} 25 |
26 |

Start editing to see some magic happen!

27 |
28 | ); 29 | } 30 | 31 | 32 | // styles.css 33 | // .App { 34 | // font-family: sans-serif; 35 | // text-align: center; 36 | // } 37 | 38 | // .starContainer { 39 | // display: flex; 40 | // } 41 | // .star { 42 | // width: 20px; 43 | // height: 20px; 44 | // border: 1px solid; 45 | // /* sbackground: yellow; */ 46 | // margin-right: 5px; 47 | // } 48 | 49 | // .highlight { 50 | // background: red; 51 | // } 52 | -------------------------------------------------------------------------------- /React_carousel.jsx: -------------------------------------------------------------------------------- 1 | import "./styles.css"; 2 | import React, { useState } from "react"; 3 | 4 | export default function App() { 5 | const [startIndex, setStartIndex] = useState(0); 6 | const handleClick = function (e) { 7 | if (e.target.className === "forward") { 8 | if (startIndex >= 2) { 9 | setStartIndex(0); 10 | return; 11 | } 12 | setStartIndex((prev) => prev + 1); 13 | } else if (e.target.className === "back") { 14 | if (startIndex <= 0) { 15 | setStartIndex(2); 16 | return; 17 | } 18 | setStartIndex((prev) => prev - 1); 19 | } 20 | 21 | console.log(e.target.className); 22 | }; 23 | 24 | return ( 25 |
26 | 27 | {/* {`section ${selected && 'section_selected'}`} */} 28 |
29 | Slide 1 30 |
31 |
32 | Slide 2 33 |
34 |
35 | Slide 3 36 |
37 | 38 |
39 | ); 40 | } 41 | 42 | 43 | /*styles.js 44 | .App { 45 | font-family: sans-serif; 46 | text-align: center; 47 | position: relative; 48 | padding: 0px; 49 | margin: 0px; 50 | } 51 | 52 | .slides { 53 | height: 100px; 54 | border: 1px solid; 55 | line-height: 100px; 56 | display: none; 57 | } 58 | 59 | .slide1 { 60 | background: red; 61 | } 62 | 63 | .slide2 { 64 | background: yellow; 65 | } 66 | 67 | .slide3 { 68 | background: green; 69 | } 70 | 71 | .active { 72 | display: block; 73 | } 74 | 75 | .back { 76 | position: absolute; 77 | left: 0; 78 | top: 50px; 79 | transform: translate(0%, -50%); 80 | } 81 | .forward { 82 | position: absolute; 83 | right: 0; 84 | top: 50px; 85 | transform: translate(0%, -50%); 86 | } 87 | */ 88 | -------------------------------------------------------------------------------- /Remove K Digits.js: -------------------------------------------------------------------------------- 1 | 2 | // ===================== Problem Statement ================================================================= 3 | 4 | /* 5 | Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. 6 | 7 | Note: 8 | The length of num is less than 10002 and will be ≥ k. 9 | The given num does not contain any leading zero. 10 | Example 1: 11 | 12 | Input: num = "1432219", k = 3 13 | Output: "1219" 14 | Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. 15 | Example 2: 16 | 17 | Input: num = "10200", k = 1 18 | Output: "200" 19 | Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. 20 | Example 3: 21 | 22 | Input: num = "10", k = 2 23 | Output: "0" 24 | Explanation: Remove all the digits from the number and it is left with nothing which is 0. 25 | */ 26 | 27 | 28 | 29 | 30 | //================================================= Solution ================================================= 31 | 32 | 33 | 34 | /** 35 | * @param {string} num 36 | * @param {number} k 37 | * @return {string} 38 | */ 39 | var removeKdigits = function(num, k) { 40 | 41 | if(num.length === k){ 42 | return '0'; 43 | } 44 | 45 | while(k > 0){ 46 | for(let i = 0; i< num.length; i++){ 47 | if(num[i] > num[i+1] || i+1 === num.length ){ 48 | num = num.replace(num[i], '') 49 | break; 50 | } 51 | } 52 | k--; 53 | } 54 | 55 | num = num.replace(/^0+/, ''); 56 | return num === '' ? '0' : num; 57 | }; 58 | -------------------------------------------------------------------------------- /Single Element in a Sorted Array.js: -------------------------------------------------------------------------------- 1 | // ===================== Problem Statement ================================================================= 2 | 3 | /* 4 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [1,1,2,3,3,4,4,8,8] 11 | Output: 2 12 | Example 2: 13 | 14 | Input: [3,3,7,7,10,11,11] 15 | Output: 10 16 | 17 | 18 | Note: Your solution should run in O(log n) time and O(1) space. 19 | */ 20 | 21 | 22 | 23 | 24 | //================================================= Solution ================================================= 25 | 26 | 27 | /** 28 | * @param {number[]} nums 29 | * @return {number} 30 | */ 31 | var singleNonDuplicate = function(nums) { 32 | let numLesngth = nums.length 33 | for(let i = 0; i< numLesngth; i = i + 2){ 34 | if(nums[i] !== nums[i+1]){ 35 | return nums[i] 36 | } 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Singleton_design-patter.js: -------------------------------------------------------------------------------- 1 | class Singleton { 2 | 3 | constructor(name) { 4 | this.name = name; 5 | } 6 | 7 | static createInstance(name) { 8 | if (!this._instance) { 9 | this._instance = new Singleton(name) 10 | } 11 | return this._instance 12 | } 13 | } 14 | 15 | console.log(Singleton.createInstance('raj')) //raj 16 | console.log(Singleton.createInstance('vikram')) //raj 17 | -------------------------------------------------------------------------------- /Sorting_with_Recursion.js: -------------------------------------------------------------------------------- 1 | //============Bubble sort using recursion======================= 2 | 3 | const bubbleSort = function(arr, r = arr.length, c = 0) { 4 | if (r === 0) { 5 | return 6 | } else if (c < r) { 7 | if (arr[c] > arr[c + 1]) { //swap 8 | let temp = arr[c + 1] 9 | arr[c + 1] = arr[c]; 10 | arr[c] = temp 11 | } 12 | bubbleSort(arr, r, c + 1) //check for swap till c= r) { 30 | return max 31 | } else if (arr[index] > max.value) { 32 | max.value = arr[index]; 33 | max.index = index; 34 | } 35 | return findMax(arr, r, index + 1, max); // return the max with index 36 | } 37 | 38 | const swapToLastWithIndex = function(arr, r, index) { //swap arr[r] with max index 39 | const temp = arr[index]; 40 | arr[index] = arr[r]; 41 | arr[r] = temp; 42 | } 43 | 44 | const selectionSort = function(arr, r = arr.length - 1) { 45 | // take the largest element and swap with the last place 46 | 47 | if (r === 0) { 48 | return arr 49 | } 50 | let max = findMax(arr, r) 51 | swapToLastWithIndex(arr, r, max.index) 52 | return selectionSort(arr, r - 1) 53 | } 54 | 55 | console.log(selectionSort([2, 3, 1, 4, 6, 5])) 56 | 57 | -------------------------------------------------------------------------------- /SystemDesign_NewsFeed.js: -------------------------------------------------------------------------------- 1 | 1) Component Architecture: { 2 | Feed component => Parent 3 | individual components 4 | header => author => avatar, 5 | name, 6 | time 7 | Content => media / text 8 | like => [likedUser] 9 | comment 10 | share 11 | 12 | } 13 | 14 | ==================== 15 | 16 | 2) Data Model { 17 | feed { 18 | id: number, 19 | date: number, 20 | author: Author {}, 21 | comment: Comment[], 22 | content: String, 23 | media: Media[] 24 | 25 | } 26 | Author { 27 | authorId, 28 | name 29 | } 30 | Media { 31 | type: img | video, 32 | url 33 | } 34 | Comment { 35 | id: number, 36 | text: 'string', 37 | author: Author {}, 38 | time: number, 39 | content: string, 40 | media: Media[] 41 | } 42 | } 43 | 44 | ==================== 45 | 46 | 3) APIs: { 47 | GET feed data(userId, ): { 48 | getFeedData: { 49 | pageNo., 50 | totalPages, 51 | data: [] 52 | } 53 | get Comment Data(feedId) { 54 | comment: Commnet[] 55 | id: number 56 | } 57 | } 58 | 59 | POST: { 60 | addComment: { 61 | content: string, 62 | media: Media[], 63 | parentId: number, 64 | } 65 | 66 | like / dislike: { 67 | like: boolean, 68 | feedId: number, 69 | userId: number, 70 | }, 71 | } 72 | } 73 | 74 | ==================== 75 | 76 | 4) Pagination { 77 | Virtual Scroll, 78 | infinite scroll 79 | } 80 | 81 | ==================== 82 | 83 | 5) Data refresh: { 84 | long polling, 85 | web sockets, 86 | Server Sent Events: Preferred in this 87 | case. 88 | } 89 | 90 | ==================== 91 | 92 | 6) Optimization: { 93 | infiniteScroll, 94 | SSE, 95 | Img type and size, 96 | PWA, 97 | caching, 98 | } 99 | 100 | -------------------------------------------------------------------------------- /Valid_Perfect_Square.js: -------------------------------------------------------------------------------- 1 | // ===================== Problem Statement ================================================================= 2 | 3 | /* 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | 6 | Note: Do not use any built-in library function such as sqrt. 7 | 8 | Example 1: 9 | 10 | Input: 16 11 | Output: true 12 | Example 2: 13 | 14 | Input: 14 15 | Output: false 16 | */ 17 | 18 | 19 | 20 | 21 | //================================================= Solution ================================================= 22 | 23 | 24 | 25 | 26 | /** 27 | * @param {number} num 28 | * @return {boolean} 29 | */ 30 | // Method 1: 31 | 32 | var isPerfectSquare = function(num) { 33 | if ((Math.sqrt(num)*10) % 10 === 0){ 34 | return true; 35 | } 36 | return false; 37 | }; 38 | 39 | 40 | // Method 2: 41 | 42 | var isPerfectSquare = function(num) { 43 | let i = 1; 44 | while(i*i < num){ 45 | i++ 46 | } 47 | return i*i === num; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /currying.js: -------------------------------------------------------------------------------- 1 | //currying for fixed legnth arguments 2 | 3 | function sum(a, b, c) { 4 | return a + b + c; 5 | } 6 | 7 | const curry = (cb) => { 8 | 9 | return function curried(...args) { 10 | if (args.length >= cb.length) { 11 | return cb(...args) 12 | } else { 13 | return function(...args2) { 14 | return curried(...args, ...args2) 15 | } 16 | } 17 | 18 | } 19 | 20 | } 21 | let curriedSum = curry(sum); 22 | console.log(curriedSum(1, 2, 3)); // 6, still callable normally 23 | console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg 24 | console.log(curriedSum(1)(2)(3)); // 6, full currying 25 | 26 | 27 | /* 28 | 29 | //Currying with variable length arguments 30 | 31 | function sum(...args) { 32 | return args.reduce((init, acc) => init + acc ) 33 | } 34 | 35 | const curry = (cb) => { 36 | let cacheArgs = []; 37 | return function curried(...args) { 38 | if (args.length === 0) { 39 | let cachedArgsCopy = [...cacheArgs]; 40 | cacheArgs.length = 0; 41 | return cb(...cachedArgsCopy); 42 | } else { 43 | cacheArgs.push(...args) 44 | return function(...args2) { 45 | return curried(...args2) 46 | } 47 | } 48 | 49 | } 50 | } 51 | 52 | let curriedSum = curry(sum); 53 | 54 | console.log(curriedSum(1, 2, 3, 4)()); // 6, still callable normally 55 | console.log(curriedSum(1)(2, 3)()); // 6, currying of 1st arg 56 | console.log(curriedSum(1)(2)(3)(9)(1)(0)()); // 6, full currying */ 57 | -------------------------------------------------------------------------------- /inheritance_functional_and_class.js: -------------------------------------------------------------------------------- 1 | function Car(wheels) { 2 | this.wheels = wheels; 3 | } 4 | 5 | 6 | function Honda(type, wheels) { 7 | Car.call(this, wheels) //call Car function with this pointing to Honda Object. This makes Honda this as {wheels, type} 8 | this.type = type; 9 | } 10 | 11 | Honda.prototype = Object.create(Car.prototype); // assign Honda.protoype to Car.prototype. Use Object.create to make a copy to avoid sharing the same prototype as objects in javascript are referenced. 12 | Honda.prototype.constructor = Honda; // assing constructor property back which was overriden on the above step 13 | const hondaCity = new Honda("sedan", "4"); 14 | 15 | console.log(hondaCity) 16 | 17 | /* class CarClass { 18 | constructor(wheels) { 19 | this.wheels = wheels; 20 | } 21 | } 22 | 23 | class HondaClass extends CarClass { 24 | 25 | constructor(type, wheels) { 26 | super(wheels); 27 | this.type = type; 28 | } 29 | 30 | } 31 | 32 | const hondaCity2 = new HondaClass("sedan", "4"); 33 | 34 | console.log(hondaCity2); */ 35 | -------------------------------------------------------------------------------- /interchange-key-value.js: -------------------------------------------------------------------------------- 1 | const initialObj = { 2 | a: [1, 2, 3], 3 | b: [2, 3, 5], 4 | c: [1, 5], 5 | d: [2, 3, 5] 6 | } 7 | 8 | /* let finalObj = {} */; //Edit this line 9 | 10 | 11 | /* 12 | OUTPUT - 13 | { 14 | "1" : ["a","c"], 15 | "2" : [“a”, "b", "d"], 16 | "3" : ["a","b","d"], 17 | "5" : ["b","c","d"] 18 | } 19 | */ 20 | 21 | 22 | 23 | 24 | const flattenArr = (inputArr) => { 25 | let flattednedArr = inputArr.reduce((acc, item) => { 26 | return [...acc, ...item]; 27 | },[]) 28 | return flattednedArr; 29 | } 30 | 31 | const manipulate = function(inputObj) { 32 | 33 | let nestedKeysArray = Object.values(inputObj); 34 | let keysArr = flattenArr(nestedKeysArray); 35 | let uniqueKeys = [...new Set(keysArr)]; 36 | let originalKeys = Object.keys(inputObj); 37 | 38 | return uniqueKeys.reduce((acc, item) => { 39 | let valueList = originalKeys.filter(key => { 40 | if (inputObj[key].includes(item)) { 41 | return key; 42 | } 43 | }) 44 | acc[item] = valueList 45 | return acc 46 | },{}); 47 | 48 | 49 | } 50 | 51 | console.log(manipulate(initialObj)); 52 | -------------------------------------------------------------------------------- /minLengthUnsortedArray.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. 3 | 4 | Return the shortest such subarray and output its length. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [2,6,4,8,10,9,15] 11 | Output: 5 12 | Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. 13 | Example 2: 14 | 15 | Input: nums = [1,2,3,4] 16 | Output: 0 17 | Example 3: 18 | 19 | Input: nums = [1] 20 | Output: 0 21 | */ 22 | 23 | /** 24 | * @param {number[]} nums 25 | * @return {number} 26 | */ 27 | 28 | var findUnsortedSubarray = function(nums) { 29 | 30 | let start = 0; 31 | let end = nums.length - 1; 32 | 33 | for(let i = 0; i< nums.length; i++){ //Find the start index of unsorted arr 34 | if(nums[i] > nums[i+1]) { 35 | start = i; 36 | break; 37 | } else if(i === nums.length-1) { 38 | return 0 39 | } 40 | } 41 | 42 | for(let i = nums.length -1; i > 0; i--){ //find the end index of unsorted arr 43 | if(nums[i] < nums[i-1]) { 44 | end = i; 45 | break; 46 | } 47 | } 48 | 49 | const unsortedArr = nums.slice(start, end + 1); //slice to get the unsorted arr 50 | let min = Infinity; 51 | let max = -Infinity; 52 | 53 | for(let i = 0; i < unsortedArr.length; i++){ 54 | if(unsortedArr[i] < min) { //Find min of the arr > 55 | min = unsortedArr[i] 56 | } 57 | if(unsortedArr[i] > max) { //find max of the arr 58 | max = unsortedArr[i] 59 | } 60 | } 61 | 62 | for(let i = 0; i < start; i++) { 63 | if(nums[i] > min) { //slide start index to left if min is < nums[i] 64 | start = i; 65 | break; 66 | } 67 | } 68 | 69 | for(let i = nums.length - 1; i > end; i--) { 70 | if(nums[i] < max) { //slide end index to right if max is > nums[i] 71 | end = i; 72 | break; 73 | } 74 | } 75 | 76 | return end - start + 1 77 | }; 78 | 79 | const testArr = [2,6,4,8,10,9,15]; 80 | findUnsortedSubarray(testArr); 81 | -------------------------------------------------------------------------------- /overlapping_elements.js: -------------------------------------------------------------------------------- 1 | let test = [ 2 | [1, 5], 3 | [5, 6], 4 | [5, 10], 5 | [13, 18], 6 | [11, 17] 7 | ] 8 | 9 | const getOverLaps = (arr) => { 10 | let result = []; 11 | arr.sort((itemA, itemB) => { 12 | return itemA[0] - itemB[0]; 13 | }) 14 | for (let i = 0; i < arr.length - 1; i++) { 15 | if (arr[i][1] >= arr[i + 1][0]) { 16 | let greaterLastElement = Math.max(arr[i][1], arr[i + 1][1]); 17 | result = [arr[i][0], greaterLastElement]; 18 | arr.splice(i, 2, result); 19 | i-- 20 | 21 | } 22 | } 23 | console.log(arr); 24 | return arr; 25 | } 26 | 27 | 28 | getOverLaps(test); 29 | -------------------------------------------------------------------------------- /pollyfill-Promise.js: -------------------------------------------------------------------------------- 1 | class CustomPromise { 2 | 3 | constructor(executor) { 4 | this.successValue = null; 5 | this.errorValue = null; 6 | this.contextOfCB = null; 7 | const resolve = (successValue) => { // assign the success value to a variable that can be accessed in then function 8 | if (!this.successValue && !this.errorValue) { 9 | this.successValue = successValue; 10 | if (this.contextOfCB) { 11 | this.contextOfCB(this.successValue); // call the stored CB when the promise is resolved asynchronously 12 | } 13 | } 14 | } 15 | const reject = (err) => { 16 | if (!this.successValue && !this.errorValue) { 17 | this.errorValue = err; 18 | if (this.contextOfCB) { 19 | this.contextOfCB(this.errorValue); 20 | } 21 | } 22 | 23 | } 24 | 25 | executor(resolve, reject); 26 | 27 | } 28 | 29 | then(cb) { // just pass the successValue to the cb 30 | if (this.successValue) { 31 | cb(this.successValue) 32 | } else { 33 | this.contextOfCB = cb //in case promise is reolved asynchronously this.successValue will not be immediately available. Store it. 34 | } 35 | 36 | return this 37 | } 38 | catch (cb) { 39 | if (this.errorValue) { 40 | cb(this.errorValue) 41 | } else { 42 | this.contextOfCB = cb 43 | } 44 | 45 | return this 46 | } 47 | } 48 | 49 | 50 | const testProm = new CustomPromise((res, rej) => { 51 | 52 | setTimeout(() => { 53 | res("Success1"); 54 | }, 0) 55 | 56 | //rej("failure"); 57 | }) 58 | 59 | /* console.log(testProm); */ 60 | testProm.then(res => console.log(res)) 61 | //testProm.then(res => console.log(res)).catch(err => console.log(err)) 62 | -------------------------------------------------------------------------------- /polyfill_myBind.js: -------------------------------------------------------------------------------- 1 | const userInfo = { 2 | firstName: "Raj", 3 | middleName: "Vikram", 4 | lastName: "Singh" 5 | } 6 | 7 | function getUnserInfo(text){ 8 | console.log(text, this.firstName + " " + this.middleName + " " + this.lastName) 9 | } 10 | 11 | getUnserInfo(); //undefined 12 | 13 | const getUserInfoWithContext = getUnserInfo.bind(userInfo, "My Name is"); 14 | 15 | getUserInfoWithContext(); // Raj Vikram Singh 16 | 17 | 18 | /* Bind Polyfill */ 19 | 20 | Function.prototype.myBind = function(context, ...args) { 21 | //this here will be the function that will invoke myBind 22 | return ()=> { // use arrow function to preserve this 23 | this.call(context, ...args); 24 | } 25 | } 26 | 27 | 28 | const getUserInfoWithMyBind = getUnserInfo.myBind(userInfo, "full name"); 29 | 30 | getUserInfoWithMyBind(); // full name, Raj Vikram Singh 31 | -------------------------------------------------------------------------------- /reduce-pollyfill.js: -------------------------------------------------------------------------------- 1 | let testArray = [1,2,3,4]; 2 | 3 | Array.prototype.myReduce = function(cb, initial) { 4 | if (typeof cb !== "function" || !this.length) { 5 | console.log("reduce not used correclty"); 6 | return; 7 | } 8 | let self = this; 9 | let accumulator = initial; 10 | let i = 0; 11 | if (!initial) { 12 | accumulator = self[0]; 13 | i = 1; 14 | } 15 | 16 | for (i; i < self.length; i++) { 17 | accumulator = cb(accumulator, self[i]); 18 | } 19 | 20 | return accumulator; 21 | 22 | } 23 | 24 | const logic = (a, b) => a + b; 25 | 26 | console.log(testArray.myReduce(logic)); 27 | -------------------------------------------------------------------------------- /remove_duplicate_objects_in_Array.js: -------------------------------------------------------------------------------- 1 | /* Create an object {
 Freshworks: 2,
 Amazon: 2,
 Google: 2
}
 that will list all the companies with the unique employee count */ 2 | 3 | const empData = [{
 company: "Freshworks",
 id: 1
}, {
 company: "Amazon",
 id: 1
}, {
 company: "Google",
 id: 1
}, {
 company: "Freshworks",
 id: 2
}, {
 company: "Freshworks",
 id: 1
}, {
 company: "Amazon",
 id: 2
}, {
 company: "Google",
 id: 3
}];
 4 | 5 | 6 | const uniqueEmpCount = (empData)=> { 7 | 8 | const uniqueDataList =[]; 9 | // This loop removes duplicate objects from array list 10 | empData.forEach(item=>{ 11 | let stringItem = JSON.stringify(item); 12 | let stringUniqueDataList = JSON.stringify(uniqueDataList); 13 | if(!(stringUniqueDataList.includes(stringItem) )){ 14 | uniqueDataList.push(item); 15 | } 16 | }) 17 | 18 | let result = {}; 19 | uniqueDataList.forEach(item => { 20 | if(result[item.company]){ 21 | result[item.company] +=1 22 | }else { 23 | result[item.company] = 1 24 | } 25 | }) 26 | return result; 27 | } 28 | 29 | 30 | console.log(uniqueEmpCount(empData)); 31 | -------------------------------------------------------------------------------- /tekn_ProblemSolvingRound.js: -------------------------------------------------------------------------------- 1 | //compose(f1, f2, …, fn)(value) // f1(f2(..fn(value))) 2 | 3 | const addOne = n => n + 1; 4 | const square = n => n * n; 5 | 6 | 7 | const compose = function(...args) { 8 | 9 | return function(value) { 10 | let result = value; 11 | for (let i = args.length -1 ; i >= 0; i--) { 12 | result = args[i](result) 13 | } 14 | return result; 15 | } 16 | 17 | } 18 | 19 | console.log(compose(addOne, square)(5)) 20 | 21 | 22 | 23 | //Given an array of integers, print the leaders in the array. - 24 | const testArr = [12, 45, 78, 450, 100, 120, 90, 40]; // 120, 90, 40 25 | 26 | /// Order of execution O(n) 27 | const findLeader = function(input) { 28 | const leader = []; 29 | for (let i = input.length - 1; i >= 0; i--) { 30 | if (leader.length === 0) { 31 | leader.push(input[i]) 32 | } else if (leader[0] < input[i]) { 33 | leader.unshift(input[i]); 34 | } 35 | 36 | } 37 | return leader 38 | } 39 | 40 | 41 | console.log(findLeader(testArr)); 42 | 43 | //Brute Force 44 | /* 45 | const findLeader = function(input) { 46 | const leader = []; 47 | input.forEach((item, index ) => { 48 | let remainingArr = input.slice(index); 49 | let lead = remainingArr.find(remainingItem => remainingItem > item) 50 | if(!lead){ 51 | leader.push(item); 52 | } 53 | }) 54 | 55 | return leader; 56 | } 57 | 58 | console.log(findLeader(testArr)); */ 59 | -------------------------------------------------------------------------------- /useWindowSize_customHook.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | 3 | export default function App() { 4 | const { width, height } = useWindowSize(); 5 | return ( 6 |
7 |

Hello CodeSandbox

8 |

width {width}

9 |

height {height}

10 |
11 | ); 12 | } 13 | 14 | function useWindowSize() { 15 | const [windowSize, setWindowSize] = useState({ 16 | width: window.innerWidth, 17 | height: window.innerHeight 18 | }); //initialize the window size 19 | 20 | useEffect(() => { 21 | function handleWindowResize() { 22 | setWindowSize({ width: window.innerWidth, height: window.innerHeight }); 23 | } 24 | window.addEventListener("resize", handleWindowResize); // register event listener on component mount 25 | return () => window.removeEventListener("resize", handleWindowResize); // remove event listener when component is unmounted 26 | }, []); 27 | return windowSize; 28 | } 29 | -------------------------------------------------------------------------------- /vmware_remove_charBeforeHash.js: -------------------------------------------------------------------------------- 1 | const S1 = 'ab#c#d#'; 2 | const S2 = 'ad#c'; 3 | 4 | const makeNewList = function(list, newList) { 5 | list.forEach((item, index) => { 6 | if (item === '#') { 7 | newList.pop(); 8 | } else { 9 | newList.push(item); 10 | } 11 | }) 12 | } 13 | 14 | const compareString = function(S1, S2) { 15 | const S1List = S1.split(""); 16 | const S2List = S2.split(""); 17 | const newSl1 = []; 18 | const newSl2 = []; 19 | 20 | makeNewList(S1List, newSl1); 21 | makeNewList(S2List, newSl2); 22 | 23 | const S1String = newSl1.join(""); 24 | const S2String = newSl2.join(""); 25 | console.log(S1String, S2String); // "a", "ac" 26 | return S1String === S2String; 27 | } 28 | 29 | 30 | 31 | console.log(compareString(S1, S2)); 32 | --------------------------------------------------------------------------------