Skip to content

Algorithms

Worked solutions to LeetCode daily challenges and classic interview problems — dynamic programming, graphs, trees, strings and more, mostly implemented in Go.

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…

Dungeon Game

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…

Permutation Sequence

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…

Longest Duplicate Substring

Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.) Return any…

H-Index II

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…

Surrounded Regions

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…

Validate IP Address

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…

Search in a Binary Search Tree

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…

Cheapest Flights Within K Stops

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…

Largest Divisible Subset

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 %…

Insert Delete GetRandom O(1)

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.…

Sort Colors

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…

Median Stream

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),…

Search Insert Position

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 Lists

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…

Is Subsequence

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…

Power of Two

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…

Coin Change 2

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…

Queue Reconstruction by Height

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…

Random Pick with Weight

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…

String Compression

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…

Longest Palindromic Subsequence

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"…

Reverse String

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…

Two City Scheduling

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…

The k-th Lexicographical String of All Happy Strings of Length n

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…

Delete Node in a Linked List

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 Binary Tree

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…

Edit Distance

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…

K Closest Points to Origin

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…

Course Schedule

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…

Counting Bits

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…

Possible Bipartition

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,…

Contiguous Array

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…

Uncrossed Lines

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…

Construct Binary Search Tree from Preorder Traversal

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…

Count of Smaller Numbers After Self

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…

Interval List Intersections

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.…

Sort Characters By Frequency

Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice…

Count Square Submatrices with All Ones

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…

Kth Smallest Element in a BST

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…

Online Stock Span

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…

Permutation in String

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…

Find All Anagrams in a String

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…

Odd Even Linked List

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…

Maximum Sum Circular Subarray

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 Trie (Prefix Tree)

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.…

Remove K Digits

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…

Single Element in a Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.…

Flood Fill

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)…

Binary Trees With Factors

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…

Find the Town Judge

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:…

K-th Smallest in Lexicographical Order

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:…

Lexicographical Numbers

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…

Valid Perfect Square

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…

Check If It Is a Straight Line

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…

Cousins in Binary Tree

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…

Majority Element

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…

First Unique Character in a String

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 =…

Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Example 2:…

Ransom Note

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…

Jewels and Stones

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…

First Bad Version

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…

Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

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…

Binary Tree Maximum Path Sum

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…

First Unique Number

You have a queue of integers, you need to retrieve the first unique integer in the queue. Implement the FirstUnique class: FirstUnique(int[] nums)…

Maximal Square

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…

Longest Common Subsequence

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…

Jump Game

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…

LRU Cache

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…

Bitwise AND of Numbers Range

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…

Subarray Sum Equals K

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 =…

Leftmost Column with at Least a One

(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…

Construct Binary Search Tree from Preorder Traversal

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…

Search in Rotated Sorted Array

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…

Minimum Path Sum

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.…

Number of Islands

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…

Valid Parenthesis String

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…

Product of Array Except Self

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…

Perform String Shifts

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…

Contiguous Array

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]…

Last Stone Weight

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…

Diameter of Binary Tree

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…

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Example: k minStack = new MinStack(); minStack.push(-2);…

Backspace String Compare

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:…

Middle of the Linked List

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…

Counting Elements

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:…

Group Anagrams

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…

Best Time to Buy and Sell Stock II

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…

Move Zeroes

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:…

Maximum Subarray

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:…

Happy Number

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,…

Single Number

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…

Remove Duplicate Letters

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…

Next Greater Element III

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…

Wiggle Sort II

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…

Next Greater Element II

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…

Next Greater Element I

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

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…

Maximum Number of Balloons

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…

Find Words That Can Be Formed by Characters

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…

Container With Most Water

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…

Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and ' '. The matching should cover the entire…

String to Integer (atoi)

mplement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace…

Longest Palindromic Substring

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…

Maximum Nesting Depth of Two Valid Parentheses Strings

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…

Delete Nodes And Return Forest

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…

Corporate Flight Bookings

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…

Smallest Sufficient Team

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.…

Relative Sort Array

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…

Lowest Common Ancestor of Deepest Leaves

Given a rooted binary tree, return the lowest common ancestor of its deepest leaves. Recall that: Example 1: Example 2: Example 3: Constraints: Solution…

Longest Well-Performing Interval

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…

Construct Binary Search Tree from Preorder Traversal

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…

Partition Equal Subset Sum

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…

Coin Change 2

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…

Number of Segments in a String

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…

Longest String Chain

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…

Last Stone Weight II

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…

Minimum Domino Rotations For Equal Row

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…

Maximize Sum Of Array After K Negations

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…

Magical Candy Bags

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…

Clumsy Factorial

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…

Queries on a Permutation With Key

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…

Longest Duplicate Substring

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

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…

Find the Closest Palindrome

Given an integer n, find the closest integer (not including itself), which is a palindrome. The 'closest' is defined as absolute difference minimized…

Binary String With Substrings Representing 1 To N

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,…

Triples with Bitwise AND Equal To Zero

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…

Time Based Key-Value Store

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,…

String Without AAA or BBB

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…

Revenue Milestones

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…

Minimum Cost For Tickets

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…

Best Sightseeing Pair

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…

Binary Prefix Divisible By 5

Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values…

Robot Bounded In Circle

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…

Pairs of Songs With Total Durations Divisible by 60

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…

Numbers With Repeated Digits

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:…

Minimum ASCII Delete Sum for Two Strings

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…

Flower Planting With No Adjacent

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…

Complement of Base 10 Integer

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…

Capacity To Ship Packages Within D Days

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…

Smallest Integer Divisible by K

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…

Prefix and Suffix Search

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…

Moving Stones Until Consecutive II

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…

Deserialize and serialize a binary tree

Write the serializer and deserializer to int array for binary tree. Binary tree structure Solution DFS solution: Tests: Output of tests: Explanation Lets…

Search in Rotated Sorted Array

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…

Partition Array Into Three Parts With Equal Sum

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…

Number of Enclaves

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…

Next Greater Node In Linked List

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…

Video Stitching

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…

Sum of Root To Leaf Binary Numbers

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…

Jump Game

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…

Jump Game II

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…

Convert to Base -2

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…

Camelcase Matching

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…

Binary Prefix Divisible By 5

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…

Two City Scheduling

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…

Stream of Characters

mplement the StreamChecker class as follows: StreamChecker(words): Constructor, init the data structure with the given words. query(letter): returns true…

Recover a Tree From Preorder Traversal

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),…

Maximum XOR of Two Numbers in an Array

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…

Maximum Sum of Two Non-Overlapping Subarrays

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.…

Matrix Cells in Distance Order

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…

Longest Arithmetic Sequence

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], ...,…

Uncrossed Lines

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…

Escape a Large Maze

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…

Edit Distance

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…

Delete Operation for Two Strings

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…

Coloring A Border

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 Linked List

Sort a linked list in O(n log n) time using constant space complexity. Example 1: Example 2: Solution Quicksort: Mergesort: Explanation Quick sort…

House Robber III

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…

House Robber II

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…

House Robber

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…

Ransom Note

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…

Reorder List

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…

LRU Cache

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…

LFU Cache

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…

Rotate Array

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…

Length of Longest Fibonacci Subsequence

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…

Fibonacci Number

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,…

Factorial Trailing Zeroes

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,…

Number of Digit One

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:…

Preimage Size of Factorial Zeroes Function

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…

Two Sum II - Input array is sorted

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…

Missing Number

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…

Intersection of Two Linked Lists

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…

First Missing Positive

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…

Find the Duplicate Number

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.…

Single Number III

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…

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…

Single Number

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…

Best Time to Buy and Sell Stock IV

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…

Best Time to Buy and Sell Stock III

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…

Best Time to Buy and Sell Stock II

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…

Best Time to Buy and Sell Stock

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…

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. Example 1: Example 2: Example 3: Solution Golang: Explanation This…

Linked List Cycle II

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…

Linked List Cycle

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…

Last updated:

Deep Learning · Algorithms · Engineering