Advertisement
amt

Qs

amt
Jan 29th, 2021 (edited)
896
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. / * ======================================================================== * /
  2. function largestUniqueSubstring(s) {
  3.     let start = 0;  // Start pointer of the sliding window
  4.     let maxLength = 0;  // Store the maximum length of substring without duplicates
  5.     let maxSubstring = "";  // Store the substring corresponding to maxLength
  6.     let charSet = new Set();  // A set to store unique characters in the current window
  7.  
  8.     for (let end = 0; end < s.length; end++) {
  9.         while (charSet.has(s[end])) {
  10.             // If duplicate found, shrink the window by removing the leftmost character
  11.             charSet.delete(s[start]);
  12.             start++;
  13.         }
  14.         // Add the current character to the set
  15.         charSet.add(s[end]);
  16.  
  17.         // Update maximum length and substring if needed
  18.         if (end - start + 1 > maxLength) {
  19.             maxLength = end - start + 1;
  20.             maxSubstring = s.substring(start, end + 1);
  21.         }
  22.     }
  23.  
  24.     return maxSubstring;
  25. }
  26.  
  27. // Example usage:
  28. console.log(largestUniqueSubstring("abcabcbb"));  // Output: "abc"
  29. console.log(largestUniqueSubstring("bbbbb"));     // Output: "b"
  30. console.log(largestUniqueSubstring("pwwkew"));    // Output: "wke"
  31.  
  32. /*
  33. To find the largest substring in a string without duplicate characters, we can use the sliding window technique. The idea is to use two pointers (start and end) to track a window of the substring that does not contain duplicates, and to keep expanding this window while updating a set of seen characters. If a duplicate is found, we shrink the window from the left side until the duplicate is removed.
  34.  
  35. Explanation:
  36. Sliding Window: We use two pointers (start and end) to represent the current window of characters that contain no duplicates.
  37. Set: A set (charSet) is used to keep track of the characters in the current window.
  38. Loop: As we expand the window with the end pointer:
  39. If the current character (s[end]) is already in the set (i.e., a duplicate is found), we shrink the window by moving the start pointer until there are no duplicates.
  40. If no duplicate is found, we update the maximum length and the corresponding substring.
  41. Example Walkthrough (largestUniqueSubstring("abcabcbb")):
  42. Initial: start = 0, end = 0, charSet = {}, maxSubstring = ""
  43. Expand to 'a': charSet = {a}, maxSubstring = "a"
  44. Expand to 'b': charSet = {a, b}, maxSubstring = "ab"
  45. Expand to 'c': charSet = {a, b, c}, maxSubstring = "abc"
  46. Duplicate 'a' found, shrink window until no duplicate: start = 1, charSet = {b, c}
  47. Repeat the process for the remaining characters, but the max substring remains "abc".
  48. Time Complexity:
  49. O(n): We visit each character at most twice (once when expanding the window, once when shrinking it), so the time complexity is linear with respect to the length of the string.
  50. Space Complexity:
  51. O(min(n, m)): n is the length of the string, and m is the size of the character set (which is at most 26 for lowercase English letters). The space complexity is determined by the size of the set charSet, so it's O(min(n, m)).
  52. */
  53. / * ======================================================================== * /
  54.  
  55. function largestTwo(arr) {
  56.     if (arr.length < 2) {
  57.         console.log("Array needs at least two elements");
  58.         return;
  59.     }
  60.  
  61.     let largest = -Infinity;
  62.     let secondLargest = -Infinity;
  63.  
  64.     for (let i = 0; i < arr.length; i++) {
  65.         if (arr[i] > largest) {
  66.             secondLargest = largest;  // update second largest to be the previous largest
  67.             largest = arr[i];  // update largest
  68.         } else if (arr[i] > secondLargest && arr[i] !== largest) {
  69.             secondLargest = arr[i];  // update second largest if it's smaller than largest but greater than the current second largest
  70.         }
  71.     }
  72.  
  73.     return [largest, secondLargest]
  74.  
  75.     console.log("Largest:", largest);
  76.     console.log("Second Largest:", secondLargest);
  77. }
  78.  
  79. // Example usage:
  80. console.log(largestTwo([-20, 20, 5, 8, 7, 3, -4])); // [20, 8]
  81. // Time Complexity O(n). Space Complexity O(1).
  82.  
  83. / * ======================================================================== * /
  84.  
  85.  
  86. function promiseAll(promises) {
  87.   return new Promise((resolve, reject) => {
  88.     // Check if the input is an iterable
  89.     if (!Array.isArray(promises)) {
  90.       return reject(new TypeError('Argument is not iterable'));
  91.     }
  92.    
  93.     let results = [];
  94.     let completedPromises = 0;
  95.  
  96.     // Iterate over the promises array
  97.     promises.forEach((promise, index) => {
  98.       // Ensure each item is a promise by wrapping with Promise.resolve
  99.       Promise.resolve(promise)
  100.         .then(value => {
  101.           results[index] = value;
  102.           completedPromises += 1;
  103.  
  104.           // If all promises have been resolved, resolve the outer promise
  105.           if (completedPromises === promises.length) {
  106.             resolve(results);
  107.           }
  108.         })
  109.         .catch(error => {
  110.           // If any promise rejects, reject the outer promise immediately
  111.           reject(error);
  112.         });
  113.     });
  114.  
  115.     // Handle the case of an empty iterable
  116.     if (promises.length === 0) {
  117.       resolve([]);
  118.     }
  119.   });
  120. }
  121.  
  122. // Example usage:
  123. const promise1 = Promise.resolve(3);
  124. const promise2 = 42;
  125. const promise3 = new Promise((resolve, reject) => {
  126.   setTimeout(resolve, 100, 'foo');
  127. });
  128.  
  129. promiseAll([promise1, promise2, promise3]).then((values) => {
  130.   console.log(values); // Output: [3, 42, 'foo']
  131. }).catch((error) => {
  132.   console.error(error);
  133. });
  134.  
  135. / * ======================================================================== * /
  136.  
  137. function promiseRace(promises) {
  138.   return new Promise((resolve, reject) => {
  139.     // Loop through each promise in the iterable
  140.     promises.forEach(promise => {
  141.       // Attach `then` and `catch` handlers to each promise
  142.       Promise.resolve(promise)
  143.         .then(resolve)
  144.         .catch(reject);
  145.     });
  146.   });
  147. }
  148.  
  149. // Example usage:
  150. const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'one'));
  151. const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'two'));
  152.  
  153. promiseRace([promise1, promise2]).then((value) => {
  154.   console.log(value); // Output: 'two'
  155. }).catch((error) => {
  156.   console.log(error);
  157. });
  158.  
  159.  
  160. export default  ReturnOnce ( num) {
  161.  
  162.    function internal (){
  163. let calledTimes = 0;
  164. if(calledTimes) {return num}
  165. else return;
  166.    }
  167.  
  168.    internal();
  169.  
  170. }
  171.  
  172. / * ======================================================================== * /
  173.  
  174.    
  175. //Write a function (getEvenAndSort) that can be
  176. // called on any array, and it returns the
  177. //subarray of only the even numbers, but
  178. //sorted.[12,3,2,1,7,6].getEvenAndSort()
  179.  
  180. getEvenAndSort(arr) {
  181.   unsortedArr = arr.filter((element)=>{
  182.     (element%2) == 0;
  183.   });
  184. return unsortedArr.sor();
  185. }
  186.  
  187. getEvenAndSort([12,3,2,1,7,6]);
  188.  
  189. ===============================================================
  190.  
  191. let prom = new Promise(function(myResolve, myReject) {
  192.   //setTimeout(function(){ alert("Hello"); }, 3000);
  193.   setTimeout(function(){ resolve("prom"); }, 1000);
  194.   setTimeout(function(){ reject(new Error("!prom")); }, 1000);
  195.  
  196. });
  197.  
  198. prom.then(function(arg) {
  199.   console.log(arg);
  200. new Promise(function(myResolve, myReject) {
  201. });
  202. });
  203.  
  204. ============================================================
  205. function foo(a){
  206. let returnValue = "";
  207. try {
  208. if(a=="bar"){
  209. throw new Error("qux");
  210. }
  211. returnValue = "try";
  212. } catch (err){
  213. returnValue = "catch";
  214. } finally {
  215. returnValue = "finally";
  216. }
  217. return returnValue;
  218. }
  219. console.log(foo('bar'));
  220. finally
  221. console.log(foo('zzz'));
  222. finally
  223. =============================================================
  224. function sayHi(fullName, callback){
  225. console.log(`Hi, ${fullName}!`);
  226. if(typeof callback === 'function'){
  227. callback();
  228. }
  229. }
  230.  
  231. function sayBye(fullName, callback){
  232. console.log(`Bye, ${fullName}!`);
  233. callback();
  234. }
  235.  
  236. function printMessage(firstName, lastName, callback){
  237. const fullName = `${firstName} ${lastName}`;
  238. if(typeof callback === 'function'){
  239. callback(fullName);
  240. }
  241. }
  242.  
  243. printMessage('John', 'Doe', x => console.log(x));
  244. John Doe
  245.  
  246. printMessage('John', Snow, sayYouKnowNothing);
  247. Uncaught ReferenceError: Snow is not defined
  248.     at <anonymous>:1:22
  249.  
  250. printMessage('John', 'Doe', sayBye);
  251. Bye, John Doe!
  252. VM1494:10 Uncaught TypeError: callback is not a function
  253.     at sayBye (<anonymous>:10:1)
  254.     at printMessage (<anonymous>:16:1)
  255.     at <anonymous>:1:1
  256.  
  257. printMessage('John', 'Doe', sayHi);
  258. Hi, John Doe!
  259. ===============================================================
  260. const x = {};
  261. x['foo']= 'bar';
  262. x.bar = {
  263. 'first': 100,
  264. 'second': 200
  265. };
  266.  
  267. console.log(x.bar['first'] + x['bar'].second);
  268.  
  269. 300
  270. =================================================================
  271.  
  272. public class MyClass {
  273.  
  274.   private Map<String,Integer> map;
  275.  
  276.   public MyClass() {
  277.  
  278.     map = new HashMap<>();
  279.  
  280.     map.put("foo", 1);
  281.  
  282.     map.put("bar", 3);
  283.  
  284.   }
  285.  
  286.   public int getValue(String input, int numRetries) throws Exception {
  287.  console.log('called with imput ', input, 'and numRetries', numRetries)
  288.     try {
  289.  
  290.       return map.get(input);
  291.  
  292.     }
  293.  
  294.     catch (Exception e) {
  295.  
  296.       if (numRetries > 3) {
  297.  
  298.         throw e;
  299.  
  300.       }
  301.  
  302.       return getValue(input, numRetries + 1);
  303.  
  304.     }
  305.  
  306.   }
  307.  
  308. }
  309. getValue("foo",0);
  310. getValue("bar",1);
  311. getValue("foo",2);
  312. getValue("bar",3);
  313.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement