-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolutions_cache.json
More file actions
28 lines (28 loc) · 17.6 KB
/
solutions_cache.json
File metadata and controls
28 lines (28 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
"add-two-promises_javascript": "/**\n * @param {Promise} promise1\n * @param {Promise} promise2\n * @return {Promise}\n */\nvar addTwoPromises = async function(promise1, promise2) {\n\n //Wait for both promises to resolve and return a new promise that resolve with the sum of values\n const [value1,value2] = await Promise.all([promise1,promise2]);\n return value1 + value2;\n \n};\n\n/**\n * addTwoPromises(Promise.resolve(2), Promise.resolve(2))\n * .then(console.log); // 4\n */",
"allow-one-function-call_javascript": "/**\n * @param {Function} fn\n * @return {Function}\n */\nvar once = function(fn) {\n let hasBeenCalled = false;\n\n return function(...args){\n if (!hasBeenCalled) {\n hasBeenCalled = true;\n return fn(...args);\n } else {\n return undefined;\n } \n } \n};\n\n/**\n * let fn = (a,b,c) => (a + b + c)\n * let onceFn = once(fn)\n *\n * onceFn(1,2,3); // 6\n * onceFn(2,3,6); // returns undefined without calling fn\n */",
"apply-transform-over-each-element-in-array_javascript": "/**\n * @param {number[]} arr\n * @param {Function} fn\n * @return {number[]}\n */\nvar map = function(arr, fn) {\n const returnedArray = []; \n for(let i=0; i < arr.length; i++){\n returnedArray[i]= fn(arr[i], i);\n } \n return returnedArray;\n};",
"array-reduce-transformation_javascript": "/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n let result = init; // Start with the initial value\n for(let i =0; i < nums.length; i ++){\n result = fn(result, nums[i]); // Apply the reducer function sequentially \n }\n return result; // Return the final accumulated value\n\n \n};",
"can-place-flowers_java": "class Solution {\n public boolean canPlaceFlowers(int[] flowerbed, int n) {\n\n int counter = 0;\n //For the first and last elements, we need not check the previous and the next adjacent positions respectively. \n for (int i= 0; i < flowerbed.length; i++){\n // Check if the current plot is empty.\n if (flowerbed[i] == 0){\n // Check if the left & right plots are empty\n boolean emptyLeftPlot = (i ==0) || (flowerbed[i-1] == 0);\n boolean emptyRightPlot = (i == flowerbed.length -1) || (flowerbed[i +1] == 0);\n\n // If both plots are empty, we can plant a flower here.\n if (emptyLeftPlot && emptyRightPlot) {\n flowerbed[i] = 1;\n counter++;\n if(counter >= n) {\n return true;\n }\n }\n }\n }\n return counter >= n;\n }\n}",
"counter-ii_javascript": "/**\n * @param {integer} init\n * @return { increment: Function, decrement: Function, reset: Function }\n */\nvar createCounter = function(init) {\n var currentCount = init;\n return { // alt : function increment(),etc..\n increment: function() {\n currentCount++;\n return currentCount\n },\n decrement: function() {\n currentCount--;\n return currentCount;\n },\n reset: function() {\n currentCount = init; \n return currentCount;\n },\n } \n};\n\n/**\n * const counter = createCounter(5)\n * counter.increment(); // 6\n * counter.reset(); // 5\n * counter.decrement(); // 4\n */",
"counter_javascript": "/**\n * @param {number} n\n * @return {Function} counter\n */\nvar createCounter = function(n) {\n let currentCount= n - 1;\n return function () {\n currentCount++;\n return currentCount;\n };\n};\n\n/** \n * const counter = createCounter(10)\n * counter() // 10\n * counter() // 11\n * counter() // 12\n */",
"create-hello-world-function_javascript": "/**\n * @return {Function}\n */\nvar createHelloWorld = function() {\n \n return function (...args) {\n return \"Hello World\";\n }\n};\n\n\n/**\n * const f = createHelloWorld();\n * f(); // \"Hello World\"\n */",
"filter-elements-from-array_javascript": "/**\n * @param {number[]} arr\n * @param {Function} fn\n * @return {number[]}\n */\nvar filter = function(arr, fn) {\n const filteredArr = [];\n for (let i= 0; i < arr.length; i++) {\n if (!fn(arr[i], i)) continue; \n filteredArr.push(arr[i]); //push into array, avoid 'holes'\n }\n return filteredArr;\n};",
"function-composition_javascript": "/**\n * @param {Function[]} functions\n * @return {Function}\n */\nvar compose = function(functions) {\n\n return function(x){\n\n // Start with the initial value\n let result = x;\n\n for(let i = functions.length -1; i >= 0; i--){\n result = functions[i](result);\n }\n return result;\n }\n};\n\n/**\n * const fn = compose([x => x + 1, x => 2 * x])\n * fn(4) // 9\n */",
"greatest-common-divisor-of-strings_java": "class Solution {\n\n public String gcdOfStrings(String str1, String str2){\n if (!(str1 +str2).equals(str2 +str1)){\n return \"\";\n }\n\n int lenGCD = gcd(str1.length(), str2.length());\n return str1.substring(0, lenGCD);\n \n }\n\n public int gcd(int len1, int len2) {\n\n while (len2 != 0){ // Euclidean Algorithm - Moves len2 into len1,replaces len2 with the remainder of len1 % len2 in each iteration\n\n int temp= len2;\n len2 = len1 % len2;\n len1 = temp;\n\n }\n return len1;\n }\n}",
"increasing-triplet-subsequence_java": "class Solution {\n public boolean increasingTriplet(int[] nums) {\n\n // first Smallest value found \n int first = Integer.MAX_VALUE;\n\n //Second smallest value found\n int second = Integer.MAX_VALUE;\n\n //Traverse array once\n for(int i= 0; i < nums.length; i ++){\n\n //Update first & second smallest number\n if (nums[i] <= first){\n first =nums[i]; \n }else if(nums[i] <= second){\n second = nums[i];\n }\n // found number bigger thn both\n else {\n return true;\n }\n \n }\n //No increasing triplet found\n return false; \n }\n}",
"interval-cancellation_javascript": "/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t){\n\n //Call fn immediatly once\n fn(...args); \n\n //Execute fn every t milliseconds \n const interval = setInterval(function(){\n fn(...args);\n }, t);\n\n //Return cancel function\n return function(){\n clearInterval(interval);\n }\n}\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 2;\n * const args = [4], t = 35, cancelTimeMs = 190;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({\"time\": diff, \"returned\": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * setTimeout(cancel, cancelTimeMs);\n * \n * setTimeout(() => {\n * console.log(result); // [\n * // {\"time\":0,\"returned\":8},\n * // {\"time\":35,\"returned\":8},\n * // {\"time\":70,\"returned\":8},\n * // {\"time\":105,\"returned\":8},\n * // {\"time\":140,\"returned\":8},\n * // {\"time\":175,\"returned\":8}\n * // ]\n * }, cancelTimeMs + t + 15) \n */",
"is-subsequence_java": "class Solution {\n public boolean isSubsequence(String s, String t) {\n\n int i =0;\n int j = 0; // Pointers for scanning strings s & t \n\n while (i < s.length() && j < t.length()){\n if (s.charAt(i) == t.charAt(j)){\n i++; //i only moves to check next character in s when a matching character is found in t\n }\n j++; //j always move forward because we continuously scan trough t\n }\n return i == s.length(); // if reached end of s, all characters were found in order\n }\n}",
"kids-with-the-greatest-number-of-candies_java": "class Solution {\n private int findLargest(int[] candies){\n //find largest element\n //initiate max as first element\n // Alternatively iterate & use Math.max\n int max = candies[0];\n for (int i= 0; i < candies.length; i++){\n if(candies[i] > max){\n //update max\n max = candies[i];\n }\n } \n return max;\n } \n public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {\n ArrayList<Boolean> result = new ArrayList<>();\n for (int i= 0; i < candies.length; i++){\n int maxCandies = findLargest(candies);\n if(candies[i] + extraCandies >= maxCandies){ \n result.add(true); \n }else{\n result.add(false);\n } \n } \n return result; \n }\n}",
"memoize_javascript": "/**\n * @param {Function} fn\n * @return {Function}\n */\nfunction memoize(fn) {\n\n //Cache to store previously computed results\n const cache = new Map();\n\n return function(...args) {\n\n //convert function arguments int a unique key\n const key = JSON.stringify(args);\n\n //If result exists in cahe, return cache value\n if (cache.has(key)){\n return cache.get(key);\n }\n\n //Otherwise compute result, store it in cache and return computed result\n const result = fn(...args);\n cache.set(key, result);\n\n return result;\n \n }\n}\n\n\n/** \n * let callCount = 0;\n * const memoizedFn = memoize(function (a, b) {\n *\t callCount += 1;\n * return a + b;\n * })\n * memoizedFn(2, 3) // 5\n * memoizedFn(2, 3) // 5\n * console.log(callCount) // 1 \n */",
"merge-strings-alternately_java": "class Solution {\n public String mergeAlternately(String word1, String word2) {\n\n StringBuilder alternateLetters = new StringBuilder();\n String mergedString;\n int pointer = 0;\n // Notes : Take length of 2 strings for iteration; use pointer initialised at 0, add each character to stringbuilder as long as\n //pointer is < word\n\n while (word1.length() + word2.length() != pointer){ //for (int pointer= 0; pointer < (word1.length() + word2.length()); pointer++){ \n if (pointer < word1.length()){\n alternateLetters.append(word1.charAt(pointer));\n }\n if (pointer < word2.length()){\n alternateLetters.append(word2.charAt(pointer));\n }\n pointer ++;\n }\n mergedString = alternateLetters.toString();\n return mergedString;\n \n }\n}",
"move-zeroes_java": "class Solution {\n public void moveZeroes(int[] nums) {\n int n = nums.length;\n int left = 0; //position for next non-zero element\n \n for (int i = 0; i < n; i ++){\n\n if (nums[i] != 0){\n int temp = nums[i];\n nums[i]= nums[left]; // move non-zero element to the left\n nums[left] = temp; // element at nums[left] goes to nums[i]\n left++; // move pointer forward\n }\n }\n \n }\n}",
"product-of-array-except-self_java": "class Solution {\n public int[] productExceptSelf(int[] nums) {\n\n int size = nums.length;\n int[] prefProduct= new int[size];\n int[] suffProduct = new int[size];\n int[] answer = new int[size];\n\n // Contruct the prefix products array\n prefProduct[0] = 1;\n for (int i =1; i < size; i ++){\n prefProduct[i]= prefProduct[i-1] * nums[i-1];\n }\n //construct the suffix products array\n suffProduct[size-1] = 1;\n for (int i= size-2; i >= 0; i--){\n suffProduct[i] = suffProduct[i+1] * nums[i+1];\n }\n //construct answer array using prefProduct[] * suffProduct[]\n for (int i = 0; i < size; i ++){\n answer[i]= prefProduct[i] * suffProduct[i];\n }\n\n return answer; \n }\n}",
"return-length-of-arguments-passed_javascript": "/**\n * @param {...(null|boolean|number|string|Array|Object)} args\n * @return {number}\n */\nvar argumentsLength = function(...args) {\n \n return args.length;\n \n};\n\n/**\n * argumentsLength(1, 2, 3); // 3\n */",
"reverse-vowels-of-a-string_java": "class Solution {\n public String reverseVowels(String s) {\n\n // Convert string to mutable char array for in-place swapping\n char [] chars = s.toCharArray();\n\n // 2 pointers method: left starts from beginning, right from end\n int left = 0;\n int right = s.length()- 1;\n \n while (left < right){\n\n //move left pointer when vowel is found\n while(left < right && !isVowel(chars[left])){\n left ++; \n }\n\n //move right pointer when vowel is found\n while(left < right && !isVowel(chars[right])){\n right --;\n } \n\n //Swap the vowels\n char temp = chars[left];\n chars[left] = chars[right];\n chars[right] = temp;\n\n //move both pointers inward after swap\n left++;\n right--;\n\n }\n\n return new String(chars); \n }\n\n //Helper method to check if charcter is a vowel\n private Boolean isVowel(char c){\n\n //indexOf return -1 if character is not found\n return \"aeiouAEIOU\".indexOf(c) != -1;\n }\n}",
"reverse-words-in-a-string_java": "class Solution {\n public String reverseWords(String s) {\n\n String [] words = s.split(\"\\\\s+\"); // split string into String array of words, without the spaces\n StringBuilder result = new StringBuilder();\n\n for (int i = words.length -1; i >=0; i--){\n result.append(words[i]);\n if (i !=0){\n result.append(\" \"); // add white space after each word until when i=0\n }\n }\n\n return result.toString().trim(); // trim()used to remove leading whitespace not removed by regex\n \n }\n}",
"sleep_javascript": "/**\n * @param {number} millis\n * @return {Promise}\n */\nasync function sleep(millis) {\n\n return new Promise(resolve => {\n setTimeout(resolve, millis);\n });\n\n}\n\n/** \n * let t = Date.now()\n * sleep(100).then(() => console.log(Date.now() - t)) // 100\n */",
"string-compression_java": "class Solution {\n public int compress(char[] chars) {\n int n = chars.length;\n int read = 0; // read pointer : scans the input array\n int write = 0; // write pointer : where we place the compressed output\n\n // Indentify goups of identical characters\n while(read < n){\n\n //Mark the start of the current group\n char current = chars[read];\n int start = read; \n\n //Count consecutive chars\n while (read < n && chars[read] == current){\n read++;\n }\n int count = read - start;\n\n //write the char\n chars[write++] = current;\n\n //if count > 1, write the digits\n if (count > 1){\n String s = String.valueOf(count); //String representation of count\n for (char c :s.toCharArray()){ //.toCharArray = converts a string to a char array\n chars[write++] = c;\n }\n }\n }\n // final compressed length of array\n return write;\n\n }\n}",
"timeout-cancellation_javascript": "/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n // Create variable timer to Schedule timer that will execute fn after t milliseconds\n const timer = setTimeout(function(){\n fn(...args);\n },t);\n\n //Return the cancel function\n //Calling this will prevent scheduled executuin \n return function(){\n clearTimeout(timer); // Cancels timer created by setTimeout\n }\n \n};\n\n/**\n * const result = [];\n *\n * const fn = (x) => x * 5;\n * const args = [2], t = 20, cancelTimeMs = 50;\n *\n * const start = performance.now();\n *\n * const log = (...argsArr) => {\n * const diff = Math.floor(performance.now() - start);\n * result.push({\"time\": diff, \"returned\": fn(...argsArr)});\n * }\n * \n * const cancel = cancellable(log, args, t);\n *\n * const maxT = Math.max(t, cancelTimeMs);\n * \n * setTimeout(cancel, cancelTimeMs);\n *\n * setTimeout(() => {\n * console.log(result); // [{\"time\":20,\"returned\":10}]\n * }, maxT + 15)\n */",
"to-be-or-not-to-be_javascript": "/**\n * @param {string} val\n * @return {Object}\n */\nvar expect = function(val) {\n return {\n toBe: function(val2){\n if (val === val2){\n return true;\n }else{\n throw new Error(\"Not Equal\");\n }\n },\n notToBe: function(val2){\n if (val !== val2){\n return true;\n }else{\n throw new Error(\"Equal\");\n }\n\n }\n };\n};\n\n/**\n * expect(5).toBe(5); // true\n * expect(5).notToBe(5); // throws \"Equal\"\n */"
}