LeetCode Problems

¡Supera tus tareas y exámenes ahora con Quizwiz!

Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false.

Fast and slow pointer. Fast moves one step and the slow moves one step. var hasCycle = function(head) { let fast = head; let slow = head; while (fast && fast.next) { fast = fast.next.next; slow = slow.next; if (fast === slow) return true; } return false; };

Contains Duplicate Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true

Create an object to store previously passed values, if value exists return true; var containsDuplicate = function(nums) { let numsTracker = {}; for (let i = 0; i < nums.length; i++) { if (numsTracker[nums[i]]){ return true } else { numsTracker[nums[i]] = 1; }; } return false; }

Given the root of a binary tree, invert the tree, and return its root. Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] Example 2: Input: root = [2,1,3] Output: [2,3,1] Example 3: Input: root = [] Output: []

helper swap function, store the left node in a variable, switch the nodes, set right to left call swap on root, 2 recursion calls on root.left and root.right var invertTree = function(root) { if (root) { swap(root); invertTree(root.left); invertTree(root.right); } return root; }; var swap = function (node) { var left = node.left; node.left = node.right; node.right = left; };

Given the head of a singly linked list, reverse the list, and return the reversed list.

while loop (head) through maintaining cur and prev; start with previousBeing null; recursively reverse, return new head of list const reverseList = (head) => { let previousNode = null; while (head) { let nextNode = head.next; head.next = previousNode; previousNode = head; head = nextNode; } return previousNode; }

Product of Array Except Self Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2: Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]

Summary: var productExceptSelf = function(nums) { // Value to increment per each index let carry = 1 // Array to return all the product values const output = Array(nums.length).fill(1) // Add products to output array starting at the front for(let i = 0; i < nums.length;i++){ output[i]*=carry carry*=nums[i] } // Reset carry carry = 1 // Add products to output array starting at the back for(let i = nums.length-1; i >= 0; i--){ output[i]*=carry carry*=nums[i] } return output };

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1]

Two iterations, one pointer and a second pointer moving through the list. Push indices to an array if equaling target var twoSum = function(nums, target) { let result = []; for (let i = 0; i < nums.length; i++) { for (let j = i+1; j < nums.length; j++) { if (nums[i] + nums[j] === target) result.push(i,j) } } return result; };

Merge Two Sorted Linked Lists Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: l1 = [], l2 = [] Output: [] Example 3: Input: l1 = [], l2 = [0] Output: [0]

instantiate a newList while both lists exist, compare values and move the next. value of that node to the next node of the LL. When one is empty, check which is null then append the other list to thee newList var mergeTwoLists = function(l1, l2) { //instantiate a new LinkedList let newList = new ListNode(0); //create a reference to the head of the new linked list let headOfNewLinkedList = newList; //while the length of both linked lists are the SAME while (l1 !== null && l2 !== null) { //chech which has the small value if (l1.val < l2.val) { newList.next = l1; l1 = l1.next; } else { newList.next = l2; l2 = l2.next; } newList = newList.next; } //if the either list is empty, append the remainder of the other LinkedList if(!l1) newList.next = l2; if(!l2) newList.next = l1; //Output: return headOfNewLinkedList.next; };

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3

recursive approach passing in node and sum. use return Math.max and recurse on left and right side, incrementing sum on each call var maxDepth = function(root) { const maxNodes = (node, sum) => { //base case = node = null if (!node) return sum //recuresive case, return Math.max(maxNodes(node.left, sum + 1), maxNodes(node.right, sum + 1)) } return maxNodes(root, 0) };

Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: Input: p = [1,2,3], q = [1,2,3] Output: true Example 2: Input: p = [1,2], q = [1,null,2] Output: false Example 3: Input: p = [1,2,1], q = [1,1,2] Output: false

var isSameTree = function(p, q) { if (!p && !q) { return true } else if (!p || !q) { return false; } if (p.val === q.val) { let leftSame = isSameTree(p.left, q.left); let rightSame = isSameTree(p.right, q.right); return leftSame && rightSame; } return false; };

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.

var rob = function(nums) { if (nums.length === 0) return 0; if (nums.length === 1) return nums[0] // Keep track of the max money we can make with x amount of houses available // dp[0] = max amount if we only have the first house to rob // dp[1] = max amount if we only have the first 2 houses to rob let dp = [nums[0], Math.max(nums[0], nums[1])]; for (let i = 2; i < nums.length; i++) { // Compare current max with the previous max // Check if the money from the current house + max of 2 houses away is greater than the current max dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]); } return dp[nums.length - 1]; };

Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: Input: arr = [1,2] Output: false Example 3: Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true

var uniqueOccurrences = function(arr) { const countMap = arr.reduce((acc, num) => { acc[num] = (acc[num] || 0) + 1 return acc }, {}) const values = Object.values(countMap) const set = new Set(values) return values.length === set.size };


Conjuntos de estudio relacionados

Chapter 54: Drugs Acting on the Upper Respiratory Tract

View Set

Graphic Design History Final (pt. 1)

View Set

Spanish 1 Unit 2/ 8.2 Grammar: Friends & Family

View Set

Introduction to Careers in Finance D9126 : 3. PRINCIPLES OF CORPORATE FINANCE

View Set

Industrialization/Industrial Revolution(*)

View Set

Chapter 22: Transoceanic Encounters and Global Connections Guided Reading

View Set

Management Exam 3 Quizlets Combined

View Set

Supply and Demand Homework Ch (04)

View Set