Single Number II
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your…
Worked solutions to LeetCode daily challenges and classic interview problems — dynamic programming, graphs, trees, strings and more, mostly implemented in Go.
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your…
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D…
The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence…
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.) Return any…
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the…
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that…
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. IPv4 addresses are canonically represented in…
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return…
There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w. Now given all the cities and flights, together…
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj %…
Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present.…
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order…
You're given a list of n integers arr[0..(n-1)]. You must compute a list output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive),…
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.…
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: Solution Let's use golang heap internal…
Given a string s and a string t, check if s is subsequence of t. A subsequence of a string is a new string which is formed from the original string by…
Given an integer, write a function to determine if it is a power of two. Example 1: Example 2: Example 3: Solution Very simple solution Performance of…
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that…
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person…
Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion…
Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element…
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. Example 1: Input: "bbbab"…
Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you…
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th…
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c']. s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string…
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which…
Invert a binary tree. Example: Input: Output: Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the…
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted…
We have a list of points on the plane. Find the K closest points to the origin (0, 0). (Here, the distance between two points on a plane is the Euclidean…
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course…
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and…
Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. Each person may dislike some other people,…
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Example 2: Solution Let's use the map to…
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line…
Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every…
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller…
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists.…
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice…
Given a m n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Example 2: Constraints: Solution Let's write simple…
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Example 1: Example 2: Follow up: What if the BST is…
Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock's price for the current day. The span of…
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations…
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the…
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the…
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C. Here, a circular array means the end of…
Implement a trie with insert, search, and startsWith methods. Example: Note: Solution Let's use the fact that we have only a-z characters in the words.…
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. Note: The…
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.…
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc)…
Given an array of unique integers, each integer is strictly greater than 1. We make a binary tree using these integers and each number may be used for any…
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. If the town judge exists, then:…
Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n. Note: 1 ≤ k ≤ n ≤ 109. Example: Input: Output:…
Given an integer n, return 1 - n in lexicographical order. For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. Please optimize your algorithm…
Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function…
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 a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. Two nodes of a binary tree are cousins if they have the…
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the…
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s =…
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Example 2:…
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…
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 are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality…
Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary…
Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node…
You have a queue of integers, you need to retrieve the first unique integer in the queue. Implement the FirstUnique class: FirstUnique(int[] nums)…
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: Output: 4 Solution This…
Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence of a string is a new string generated from the…
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum…
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the…
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. Example 1: Input: [5,7] Output: 4…
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums =…
(This problem is an interactive problem.) A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in…
Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every…
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You…
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.…
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent…
Example 1: Example 2: Example 3: Note: The string size will be in the range [1, 100]. Solution We can solve this task by the simple recursion method by…
Given an array nums of n integers where n 1, return an array output such that output[i] is equal to the product of all the elements of nums except…
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: direction can be 0 (for left…
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1]…
We have a collection of stones, each stone has a positive integer weight. Each turn, we choose the two heaviest stones and smash them together. Suppose…
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between…
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Example: k minStack = new MinStack(); minStack.push(-2);…
Given two strings S and T, return if they are equal when both are typed into empty text editors. means a backspace character. Example 1: Example 2:…
Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle…
Given an integer array arr, count element x such that x + 1 is also in arr. If there're duplicates in arr, count them seperately. Example 1: Example 2:…
Given an array of strings, group anagrams together. Example: All inputs will be in lowercase. The order of your output does not matter. Solution One of…
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete…
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Note:…
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input:…
Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer,…
Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime…
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your…
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater…
Given an unsorted array nums, reorder it such that nums[0] < nums[1] nums[2] < nums[3].... Example 1: Example 2: Follow Up: Can you do it in O(n) time…
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next…
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's…
Reverse Substrings Between Each Pair of Parentheses You are given a string s that consists of lower case English letters and brackets. Reverse the strings…
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in…
You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two…
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and ' '. The matching should cover the entire…
mplement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace…
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Example 2: Solution Let's…
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be…
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to delete, we are left with a forest…
There are n flights, and they are labeled from 1 to n. We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k…
In a project, you have a list of required skills req skills, and a list of people. The i-th person people[i] contains a list of skills that person has.…
Given two arrays arr1 and arr2 , the elements of arr2 are distinct, and all elements in arr2 are also in arr1 . Sort the elements of arr1 such that the…
Given a rooted binary tree, return the lowest common ancestor of its deepest leaves. Recall that: Example 1: Example 2: Example 3: Constraints: Solution…
We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of…
Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every…
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both…
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that…
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. Please note that the string does…
Given a list of words, each word consists of English lowercase letters. Let's say word1 is a predecessor of word2 if and only if we can add exactly one…
We have a collection of rocks, each rock has a positive integer weight. Each turn, we choose any two rocks and smash them together. Suppose the stones…
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each…
User Accepted: 2691 User Tried: 2945 Total Accepted: 2760 Total Submissions: 6124 Difficulty: Easy Given an array A of integers, we must modify the array…
You have N bags of candy. The ith bag contains arr[i] pieces of candy, and each of the bags is magical! It takes you 1 minute to eat all of the pieces of…
Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 9 8 7 6 5…
iven the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the…
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.) Return any…
HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The…
Given an integer n, find the closest integer (not including itself), which is a palindrome. The 'closest' is defined as absolute difference minimized…
Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N,…
Given an array of integers A, find the number of triples of indices (i, j, k) such that: Example 1: Note: Solution Brute force solution: Pairs solution…
Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value,…
Given two integers A and B, return any string S such that: Example 1: Example 2: Note: Solution State machine solution: Explanation Lets keep track…
We keep track of the revenue we makes every day, and we want to know on what days we hits certain revenue milestones. Given an array of the revenue on…
In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as…
Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i…
Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values…
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: The robot performs the…
In a list of songs, the i-th song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is…
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit. Example 1: Example 2:…
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. Example 1: Example 2: Note: Solution Dynamic…
You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers. paths[i] = [x, y] describes the existence of a…
Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note…
A conveyor belt has packages that must be shipped from one port to another within D days. The i-th package on the conveyor belt has a weight of…
Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. Return the…
Given many words, words[i] has weight i. Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return…
On an infinite number line, the position of the i-th stone is given by stones[i]. Call a stone an endpoint stone if it has the smallest or largest…
Write the serializer and deserializer to int array for binary tree. Binary tree structure Solution DFS solution: Tests: Output of tests: Explanation Lets…
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You…
Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums. Formally, we can partition…
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land) A move consists of walking from one land square 4-directionally to another…
We are given a linked list with head as the first node. Let's number the nodes in the list: node 1, node 2, node 3, ... etc. Each node may have a next…
You are given a series of video clips from a sporting event that lasted T seconds. These video clips can be overlapping with each other and have varied…
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if…
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum…
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum…
Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). The returned string must have no…
A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at…
Given an array A of 0s and 1s, consider N i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to…
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th…
mplement the StreamChecker class as follows: StreamChecker(words): Constructor, init the data structure with the given words. query(letter): returns true…
We run a preorder depth first search on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node),…
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. Find the maximum result of ai XOR aj, where 0 ≤ i, j < n. Could you do this…
Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M.…
We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 <= r < R and 0 <= c < C. Additionally, we are given a…
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i 1], A[i 2], ...,…
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw a straight line connecting two numbers…
In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 <= x, y < 10^6. We start at the source square and want to reach…
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted…
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one…
Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location. Two squares belong to the same…
Sort a linked list in O(n log n) time using constant space complexity. Example 1: Example 2: Solution Quicksort: Mergesort: Explanation Quick sort…
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house…
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are…
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…
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…
Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not modify the values in the list's nodes, only nodes itself…
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the…
Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the…
Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Example 2: Note: Try to come up as many solutions as you…
A sequence X 1, X 2, ..., X n is fibonacci-like if: n = 3 X i + X {i+1} = X {i+2} for all i + 2 <= n Given a strictly increasing array A of positive…
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones,…
Given an integer n, return the number of trailing zeroes in n!. Example 1: Example 2: Solution Golang: Explanation We need to calculate divisions on 5,…
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example: Solution Golang:…
Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 2 3 ... x, and by convention, 0! = 1.) For example, f(3) = 0 because 3! = 6 has no…
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function…
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Example 2: Note: Your…
Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to…
Given an unsorted integer array, find the smallest missing positive integer. Example 1: Example 2: Example 3: Note: Your algorithm should run in O(n) time…
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist.…
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that…
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your…
Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime…
Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete…
Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete…
Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete…
Say you have an array for which the i-th element is the price of a given stock on day i. If you were only permitted to complete at most one transaction…
Given a string, find the length of the longest substring without repeating characters. Example 1: Example 2: Example 3: Solution Golang: Explanation This…
Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an…
Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer pos which represents the position…