Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- / * ======================================================================== * /
- function largestUniqueSubstring(s) {
- let start = 0; // Start pointer of the sliding window
- let maxLength = 0; // Store the maximum length of substring without duplicates
- let maxSubstring = ""; // Store the substring corresponding to maxLength
- let charSet = new Set(); // A set to store unique characters in the current window
- for (let end = 0; end < s.length; end++) {
- while (charSet.has(s[end])) {
- // If duplicate found, shrink the window by removing the leftmost character
- charSet.delete(s[start]);
- start++;
- }
- // Add the current character to the set
- charSet.add(s[end]);
- // Update maximum length and substring if needed
- if (end - start + 1 > maxLength) {
- maxLength = end - start + 1;
- maxSubstring = s.substring(start, end + 1);
- }
- }
- return maxSubstring;
- }
- // Example usage:
- console.log(largestUniqueSubstring("abcabcbb")); // Output: "abc"
- console.log(largestUniqueSubstring("bbbbb")); // Output: "b"
- console.log(largestUniqueSubstring("pwwkew")); // Output: "wke"
- /*
- 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.
- Explanation:
- Sliding Window: We use two pointers (start and end) to represent the current window of characters that contain no duplicates.
- Set: A set (charSet) is used to keep track of the characters in the current window.
- Loop: As we expand the window with the end pointer:
- 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.
- If no duplicate is found, we update the maximum length and the corresponding substring.
- Example Walkthrough (largestUniqueSubstring("abcabcbb")):
- Initial: start = 0, end = 0, charSet = {}, maxSubstring = ""
- Expand to 'a': charSet = {a}, maxSubstring = "a"
- Expand to 'b': charSet = {a, b}, maxSubstring = "ab"
- Expand to 'c': charSet = {a, b, c}, maxSubstring = "abc"
- Duplicate 'a' found, shrink window until no duplicate: start = 1, charSet = {b, c}
- Repeat the process for the remaining characters, but the max substring remains "abc".
- Time Complexity:
- 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.
- Space Complexity:
- 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)).
- */
- / * ======================================================================== * /
- function largestTwo(arr) {
- if (arr.length < 2) {
- console.log("Array needs at least two elements");
- return;
- }
- let largest = -Infinity;
- let secondLargest = -Infinity;
- for (let i = 0; i < arr.length; i++) {
- if (arr[i] > largest) {
- secondLargest = largest; // update second largest to be the previous largest
- largest = arr[i]; // update largest
- } else if (arr[i] > secondLargest && arr[i] !== largest) {
- secondLargest = arr[i]; // update second largest if it's smaller than largest but greater than the current second largest
- }
- }
- return [largest, secondLargest]
- console.log("Largest:", largest);
- console.log("Second Largest:", secondLargest);
- }
- // Example usage:
- console.log(largestTwo([-20, 20, 5, 8, 7, 3, -4])); // [20, 8]
- // Time Complexity O(n). Space Complexity O(1).
- / * ======================================================================== * /
- function promiseAll(promises) {
- return new Promise((resolve, reject) => {
- // Check if the input is an iterable
- if (!Array.isArray(promises)) {
- return reject(new TypeError('Argument is not iterable'));
- }
- let results = [];
- let completedPromises = 0;
- // Iterate over the promises array
- promises.forEach((promise, index) => {
- // Ensure each item is a promise by wrapping with Promise.resolve
- Promise.resolve(promise)
- .then(value => {
- results[index] = value;
- completedPromises += 1;
- // If all promises have been resolved, resolve the outer promise
- if (completedPromises === promises.length) {
- resolve(results);
- }
- })
- .catch(error => {
- // If any promise rejects, reject the outer promise immediately
- reject(error);
- });
- });
- // Handle the case of an empty iterable
- if (promises.length === 0) {
- resolve([]);
- }
- });
- }
- // Example usage:
- const promise1 = Promise.resolve(3);
- const promise2 = 42;
- const promise3 = new Promise((resolve, reject) => {
- setTimeout(resolve, 100, 'foo');
- });
- promiseAll([promise1, promise2, promise3]).then((values) => {
- console.log(values); // Output: [3, 42, 'foo']
- }).catch((error) => {
- console.error(error);
- });
- / * ======================================================================== * /
- function promiseRace(promises) {
- return new Promise((resolve, reject) => {
- // Loop through each promise in the iterable
- promises.forEach(promise => {
- // Attach `then` and `catch` handlers to each promise
- Promise.resolve(promise)
- .then(resolve)
- .catch(reject);
- });
- });
- }
- // Example usage:
- const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'one'));
- const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'two'));
- promiseRace([promise1, promise2]).then((value) => {
- console.log(value); // Output: 'two'
- }).catch((error) => {
- console.log(error);
- });
- export default ReturnOnce ( num) {
- function internal (){
- let calledTimes = 0;
- if(calledTimes) {return num}
- else return;
- }
- internal();
- }
- / * ======================================================================== * /
- //Write a function (getEvenAndSort) that can be
- // called on any array, and it returns the
- //subarray of only the even numbers, but
- //sorted.[12,3,2,1,7,6].getEvenAndSort()
- getEvenAndSort(arr) {
- unsortedArr = arr.filter((element)=>{
- (element%2) == 0;
- });
- return unsortedArr.sor();
- }
- getEvenAndSort([12,3,2,1,7,6]);
- ===============================================================
- let prom = new Promise(function(myResolve, myReject) {
- //setTimeout(function(){ alert("Hello"); }, 3000);
- setTimeout(function(){ resolve("prom"); }, 1000);
- setTimeout(function(){ reject(new Error("!prom")); }, 1000);
- });
- prom.then(function(arg) {
- console.log(arg);
- new Promise(function(myResolve, myReject) {
- });
- });
- ============================================================
- function foo(a){
- let returnValue = "";
- try {
- if(a=="bar"){
- throw new Error("qux");
- }
- returnValue = "try";
- } catch (err){
- returnValue = "catch";
- } finally {
- returnValue = "finally";
- }
- return returnValue;
- }
- console.log(foo('bar'));
- finally
- console.log(foo('zzz'));
- finally
- =============================================================
- function sayHi(fullName, callback){
- console.log(`Hi, ${fullName}!`);
- if(typeof callback === 'function'){
- callback();
- }
- }
- function sayBye(fullName, callback){
- console.log(`Bye, ${fullName}!`);
- callback();
- }
- function printMessage(firstName, lastName, callback){
- const fullName = `${firstName} ${lastName}`;
- if(typeof callback === 'function'){
- callback(fullName);
- }
- }
- printMessage('John', 'Doe', x => console.log(x));
- John Doe
- printMessage('John', Snow, sayYouKnowNothing);
- Uncaught ReferenceError: Snow is not defined
- at <anonymous>:1:22
- printMessage('John', 'Doe', sayBye);
- Bye, John Doe!
- VM1494:10 Uncaught TypeError: callback is not a function
- at sayBye (<anonymous>:10:1)
- at printMessage (<anonymous>:16:1)
- at <anonymous>:1:1
- printMessage('John', 'Doe', sayHi);
- Hi, John Doe!
- ===============================================================
- const x = {};
- x['foo']= 'bar';
- x.bar = {
- 'first': 100,
- 'second': 200
- };
- console.log(x.bar['first'] + x['bar'].second);
- 300
- =================================================================
- public class MyClass {
- private Map<String,Integer> map;
- public MyClass() {
- map = new HashMap<>();
- map.put("foo", 1);
- map.put("bar", 3);
- }
- public int getValue(String input, int numRetries) throws Exception {
- console.log('called with imput ', input, 'and numRetries', numRetries)
- try {
- return map.get(input);
- }
- catch (Exception e) {
- if (numRetries > 3) {
- throw e;
- }
- return getValue(input, numRetries + 1);
- }
- }
- }
- getValue("foo",0);
- getValue("bar",1);
- getValue("foo",2);
- getValue("bar",3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement