Problem Summary

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Given two arrays, write a function to compute their intersection.

- Facebook - Sorting and Searching - Intersection of Two Arrays.py - Time: O(NxM) - Space: O(NxM)

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 length of both strings s and p will not be larger than 20,100. The order of output does not matter.

- Facebook - Others - Find All Anagrams in a String.py - Time: O(N) - Space: O(1), cuz limited 26 chars

Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children.

- Facebook - Trees and Graphs - Binary Tree Paths.py - Time: O(N) - Space: O(N)

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. (Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)

- Facebook - Others - Interval List Intersections.py - Time: O(N) - Space: O(N)

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 is the substring of the second string.

- Facebook - Others - Permutation in String.py - Time: O(N) - Space: O(1), cuz of limited chars

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

- Facebook - Others - Verifying an Alien Dictionary.py - Time: O(N) - Space: O(1)

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

- Facebook - Recursion - Letter Combinations of a Phone Number.py - Time: O(3^n x 4^N) - Space: O(3^n x 4^N)

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

- Facebook - Recursion - Operators - Expression Add Operators.py - Time: O(4^N) - Space: O(N)

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

- Facebook - Recursion - Permutations II.py - Time: O(N!) - Space: O(N!)

Given a collection of distinct integers, return all possible permutations.

- Facebook - Recursion - Permutations.py - Time: O(N!) - Space: O(N!)

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

- Facebook - Recursion - Remove Invalid Parentheses.py - Time: O(2^N) - Space: O(N)

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n.

- Facebook - Recursion - Strobogrammatic Number II.py - Time: O(C^N) - Space: O(C^N)

Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets.

- Facebook - Recursion - Subsets.py - Time: O(N X 2^N) - Space: O(N x 2^N)

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

- Facebook - Sorting and Searching - Divide Two Integers.py - Time: O(log2N) - Space: O(logN)

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1].

- Facebook - Sorting and Searching - Find First and Last Position of Element in Sorted Array.py - Time: O(logN) - Space: O(1)

A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞.

- Facebook - Sorting and Searching - Find Peak Element.py - Time: O(logN) - Space: O(1)

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. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

- Facebook - Sorting and Searching - First Bad Version.py - Time: O(logN) - Space: O(1)

Given two arrays, write a function to compute their intersection. What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

- Facebook - Sorting and Searching - Intersection of Two Arrays II.py - Time: O(N) - Space: O(N)

Given a collection of intervals, merge all overlapping intervals.

- Facebook - Sorting and Searching - Merge Intervals.py - Time: O(NlogN) - Space: O(N)

Implement pow(x, n), which calculates x raised to the power n (xn).

- Facebook - Sorting and Searching - Pow(x, n).py - Time: O(logN) - Space: O(logN)

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 are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n).

- Facebook - Sorting and Searching - Search in Rotated Sorted Array.py - Time: O(logN) - Space: O(N)

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

- Facebook - Trees and Graphs - Alien Dictionary.py - Time: O(C), where c is total length of all words added together - Space: O(1)

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST.

- Facebook - Trees and Graphs - Binary Search Tree Iterator.py - Time: O(1) - Space: O(h), amortized

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 in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

- Facebook - Trees and Graphs - Binary Tree Maximum Path Sum.py - Time: O(N) - Space: O(H)

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

- Facebook - Trees and Graphs - Binary Tree Right Side View.py - Time: O(N) - Space: O(H) average O(N) worst case

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right.

- Facebook - Trees and Graphs - Binary Tree Vertical Order Traversal.py - Time: O(N) - Space: O(N)

Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

- Facebook - Trees and Graphs - Clone Graph.py - Time: O(N) - Space: O(N)

Given an array w of positive integers, where w[i] describes the weight of index i(0-indexed), write a function pickIndex which randomly picks an index in proportion to its weight. For example, given an input list of values w = [2, 8], when we pick up a number out of it, the chance is that 8 times out of 10 we should pick the number 1 as the answer since it's the second element of the array (w[1] = 8).

- Sorting and Searching - Random Pick with Weight.py - Time: O(logN) - Space: O(N)

In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.

- Sorting and Searching - Rotting Oranges.py - Time: O(N) - Space: O(N) TODO: look at better approach

Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return list of lists of the suggested products after each character of searchWord is typed.

- Sorting and Searching - Search Suggestions System.py - Time: O(N) - Space: O(N)

Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.) If there are no nodes with an even-valued grandparent, return 0.

- Sum of Nodes with Even-Valued Grandparent - Trees and graphs - Time: O(N) - Space O(N)

On a single threaded CPU, we execute some functions. Each function has a unique id between 0 and N-1. We store logs in timestamp order that describe when a function is entered or exited. Each log is a string with this format: "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means the function with id 0 started at the beginning of timestamp 3. "1:end:2" means the function with id 1 ended at the end of timestamp 2. A function's exclusive time is the number of units of time spent in this function. Note that this does not include any recursive calls to child functions. The CPU is single threaded which means that only one function is being executed at a given time unit. Return the exclusive time of each function, sorted by their function id.

- Arrays and Strings - Exclusive Time of Functions.py - Time: O(N) - Space: O(N)

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, just return any of them.

- Arrays and Strings - Fraction to Recurring Decimal.py - Time: O(N) - Space: O(N)

A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word.For example, the word 'apple' becomes 'applema'. If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma".For example, the word "goat" becomes "oatgma". Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on. Return the final sentence representing the conversion from S to Goat Latin.

- Arrays and Strings - Goat Latin.py - Time: O(N^2) - Space: O(N^2)

A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1. You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface: BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed). BinaryMatrix.dimensions() returns a list of 2 elements [rows, cols], which means the matrix is rows * cols. Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.

- Arrays and Strings - Leftmost Column with at Least a One.py - Time: O(N) - Space: O(1)

Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.

- Arrays and Strings - Minimum Remove to Make Valid Parentheses.py - Time: O(N) - Space: O(N)

A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

- Arrays and Strings - Partition Labels - Time: O(N) - Space O(1) -Go through and make dict of last occurences of all characters. -Re-loop and keep counter and map of characters - Put char in map and increment counter - If char is at end of it's occurences, pop char from map - if map is empty append counter to out and reset it

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

- Arrays and Strings - Reverse String II.py - Time: O(N) - Space: O(N)

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target.

- Closest Binary Search Tree Value - Trees and graphs - Time: O(H) worst O(N) - Space O(H)

There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a network where connections[i] = [a, b] represents a connection between servers a and b. Any server can reach any other server directly or indirectly through the network. A critical connection is a connection that, if removed, will make some server unable to reach some other server.

- Critical Connections in a Network - Trees and graphs - Time: O(E) - Space O(E + V)

Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

- Design - Top K Frequent Words.py - Time: O(N) to NLogN - Space: O(N) TODO: take another look at quickselect algo or even heap

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets.

- Facebook - Arrays and Strings - 3Sum.py - Time: O(N) - Space: O(N)

Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0.

- Facebook - Arrays and Strings - Add Binary.py - Time: O(N) - Space: O(N)

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]

- Facebook - Arrays and Strings - Group Anagrams.py - Time: O(NK) or O(NKlogK) for sort approach - Space: O(NK)

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

- Facebook - Arrays and Strings - Integer to English Words.py - Time: O(N) - Space: O(1)

Given a string, find the length of the longest substring without repeating characters.

- Facebook - Arrays and Strings - Longest Substring Without Repeating Characters.py - Time: O(N) - Space: O(k)

Given a string, find the length of the longest substring T that contains at most k distinct characters.

- Facebook - Arrays and Strings - Longest Substring with At Most K Distinct Characters.py - Time: O(N) - Space: O(k)

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.

- Facebook - Arrays and Strings - Merge Sorted Array.py - Time: O(N) - Space: O(1)

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

- Facebook - Arrays and Strings - Minimum Window Substring.py - Time: O(N) - Space: O(N)

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: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

- Facebook - Arrays and Strings - Move Zeroes.py - Time: O(N) - Space: O(1)

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

- Facebook - Arrays and Strings - Multiply Strings.py - Time: O(N) - Space: O(N)

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

- Facebook - Arrays and Strings - Next Permutation.py - Time: O(N) - Space: O(1)

Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 possiblities to satisify one edit distance apart: Insert a character into s to get t Delete a character from s to get t Replace a character of s to get t

- Facebook - Arrays and Strings - One Edit Distance.py - Time: O(N) - Space: O(N)

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 nums[i].

- Facebook - Arrays and Strings - Product of Array Except Self.py - Time: O(N) - Space: O(N)

Given a file and assume that you can only read the file using a given method read4, implement a method read to read n characters. Your method read may be called multiple times.

- Facebook - Arrays and Strings - Read N Characters Given Read4 II - Call multiple times.py - Time: O(N) - Space: O(N)

Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters. Method read4: The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf. The return value is the number of actual characters read. Note that read4() has its own file pointer, much like FILE *fp in C.

- Facebook - Arrays and Strings - Read N Characters Given Read4.py - Time: O(N) - Space: O(N)

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

- Facebook - Arrays and Strings - Remove Duplicates from Sorted Array.py - Time: O(N) - Space: O(1)

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

- Facebook - Dynamic Programming - Merge Two Sorted Lists.py - Time: O(N) - Space: O(1)

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

- Facebook - Dynamic Programming - Range Sum Query 2D - Immutable.py - Time: O(N^2) - Space: O(N^2)

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).

- Facebook - Dynamic Programming - Regular Expression Matching.py - Time: O(Text * Pattern) - Space: O(Text * Pattern)

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 may be changed.

- Facebook - Dynamic Programming - Reorder List.py - Time: O(N) - Space: O(1)

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words.

- Facebook - Dynamic Programming - Word Break.py - Time: O(N^2) - Space: O(N)

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.

- Facebook - Linked Lists - Add Two Numbers.py - Time: O(N) - Space: O(N)

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

- Design - Trapping Rain Water.py - Time: O(N) - Space: O(N)

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

- Facebook - Arrays and Strings - Subarray Sum Equals K.py - Time: O(N) - Space: O(N)

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 any two nodes in a tree. This path may or may not pass through the root.

- Facebook - Trees and Graphs - Diameter of Binary Tree.py - Time: O(N) - Space: O(N)

Given a binary tree, flatten it to a linked list in-place. For example, given the following tree:

- Facebook - Trees and Graphs - Flatten Binary Tree to Linked List.py - Time: O(N) - Space: O(N)

Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B. The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.

- Facebook - Trees and Graphs - Is Graph Bipartite?.py - Time: O(Edge + Node) - Space: O(N)

Share Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)." Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

- Facebook - Trees and Graphs - Lowest Common Ancestor of a Binary Tree.py - Time: O(N) - Space: O(N)

You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier will consist only of lowercase letters, or; Each word after the identifier will consist only of digits. We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier. Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order. Return the final order of the logs.

- Reorder Data in Log Files - Arrays and Strings - Time: (AlogA) where A is lenght of logs - Space: O(A)

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root. A node is deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is that node, plus the set of all descendants of that node. Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

- Smallest Subtree with all the Deepest Nodes - Trees and graphs - Time: O(N) - Space O(N)

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 distance.) You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)

- Sorting and Searching - K Closest Points to Origin.py - Time: O(N) to klogn - Space: O(N)

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

- Arrays and Strings - Add Strings.py - Time: O(N) - Space: O(N)

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

- Facebook - Dynamic Programming - Longest Valid Parentheses.py - Time: O(N) - Space: O(N)

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

- Facebook - Arrays and Strings - Roman to Integer.py - Time: O(N) - Space: O(1)

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.

- Facebook - Arrays and Strings - String to Integer (atoi).py - Time: O(N) - Space: O(1)

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

- Facebook - Arrays and Strings - Valid Palindrome II.py - Time: O(N) - Space: O(N) because of method call, otherwise O(1)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

- Facebook - Arrays and Strings - Valid Palindrome.py - Time: O(N) - Space: O(1) or O(N)

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 dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid. IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases). However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.

- Facebook - Arrays and Strings - Validate IP Address.py - Time: O(N) - Space: O(1), but O(N) with method calls

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

- Facebook - Design - Add and Search Word - Data structure design.py - Time: O(N) - Space: O(N)

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 value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. The cache is initialized with a positive capacity.

- Facebook - Design - LRU Cache.py - Time: O(1) - Space: O(N)

Say you have an array prices 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 as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy ag

- Facebook - Dynamic Programming - Best Time to Buy and Sell Stock II.py - Time: O(N) - Space: O(1)

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.

- Facebook - Dynamic Programming - Best Time to Buy and Sell Stock.py - Time: O(N) - Space: O(1)

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.

- Facebook - Dynamic Programming - Continuous Subarray Sum.py - Time: O(N) - Space: O(N)

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.

- Facebook - Dynamic Programming - Copy List with Random Pointer.py - Time: O(N) - Space: O(N)

A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it.

- Facebook - Dynamic Programming - Decode Ways.py - Time: O(N) - Space: O(N)

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

- Facebook - Dynamic Programming - Longest Palindromic Substring.py - Time: O(N^2) - Space: O(N), or O(1) without method call

Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

- Facebook - Trees and Graphs - Convert Binary Search Tree to Sorted Doubly Linked List.py - Time: O(N) - Space: O(N)

Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

- Facebook - Trees and Graphs - Merge Accounts -Emails.py - Time: O(Sigma(N)logN), when N is length of accounts[i] - Space: O(Sigma(n))

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 lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

- Facebook - Trees and Graphs - Number of Islands.py - Time: O(N^2) - Space: O(N^2)

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

- Facebook - Trees and Graphs - Serialize and Deserialize Binary Tree.py - Time: O(N) - Space: O(N)

You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: Each 0 marks an empty land which you can pass by freely. Each 1 marks a building which you cannot pass through. Each 2 marks an obstacle which you cannot pass through.

- Facebook - Trees and Graphs - Shortest Distance from All Buildings.py - Time: O(N) - Space: O(N)

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

- Facebook - Trees and Graphs - Validate Binary Search Tree.py - Time: O(N) - Space: O(N)

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.

- Minimum Depth of Binary Tree - Trees and graphs - Time: O(N) - Space O(N)

Given two sparse matrices A and B, return the result of AB. You may assume that A's column number is equal to B's row number.

- Others - Sparse Matrix Multiplication.py - Time: O(N^2) - Space: O(N^2)

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

- Sorting and Searching - Kth Largest Element in an Array.py - Time: O(N) to klogn - Space: O(N)

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

- Sorting and Searching - Meeting Rooms II.py - Time: O(NlogNN) - Space: O(N)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

- Sorting and Searching - Merge k Sorted Lists.py - Time: O(N) - Space: O(N)

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Note:The array size can be very large. Solution that uses too much extra space will not pass the judge.

- Sorting and Searching - Random Pick Index.py - Time: O(N) - Space: O(N)

Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates). If two nodes have the same position, then the value of the node that is reported first is the value that is smaller. Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.

- Vertical Order Traversal of a Binary Tree - Trees and graphs - Time: O(N) - Space O(Nlog(N/k))


Ensembles d'études connexes

PSYC5313 Final Review In Class/Midterm

View Set

AP Human Geo Country Case Studies

View Set

Explore the Business and Administration Career Cluster

View Set

Sadlier Vocabulary Workshop Level A Unit 1-15

View Set

Math 202 : Probability and Statistics Final Test Prep

View Set

Questions I got wrong on examfx practice

View Set