Você está na página 1de 10

#

DP: Given a matrix of numbers, find a chain of monotonically


increasing numbers. Matrix elements can be chained together
with 4 adjacent elements (up, down, left, right). Problem can
also be formulated with 8 neighbors of a node.
4 neighbors of X:
*
* X *
*

8
*
*
*

neighbors of X:
* *
X *
* *

With obstructions:
| * *
* X *
| * |

Solution:
Implement to a graph problem
(Directed vs undirected)
We'll choose direceted
1. Build graph from input matrix
- each matrix element (that is not an obsctruction) is a node.
- Edge (u, v) if u < v u ----> v with weight 1.
Longest path is the solution.
Directed acyclic graph (DAG): Introduce a source node -infinity that is adjacden
t to all nodes of G by flipping the order.
Use shortest path algo by flipping the weights (DAG) and start from the introduc
ed node.
DAC (topological algorithm) is an implementation of dynamic program (Djikstra, B
ellman-Ford) except BFS.
This solution fits for dynamic problem because the solution is dynamic.
--- --#
Solution:
Firstly, ask what is the character set.
Simple mapping won't work.
Approach 1: Counting sort's counting section. ("Hashing" with h(i) = i)
Overkill unless we have info:
* String length --> Works well if strings are long
* Character set -->
Approach 2: Sort and compare
NOTE:
If hashing is your first suggestion, you will not get a job.
Seemingly random buckets are harmful.
Hashing is better for a situation where:
Character set is 1 billion, string is long but has k (small) unique characters f
rom the character set.
In Java, use StringBuilder. Java Strings are immutable.
Modified:
Two arrays of integers of large size, elements are large (big integers) in O(n)
that wil find sort(A1) != sort(A2) with high probability.

Open problem.
--- --# Tokenizer
Strings: Given a set of keywords (say, of a programming langauge),
write a function that takes a string as input and finds if it is a
keyword or an identifier (such as name of variable, class, or
function). This function will be called many times, and the keywords
are fixed. What is a good implementation of the function?
Approach
Hashmap:
Approach
Appraoch
Distinct

1:
Never. Too slow.
2: Trie
3: Finite automata
prefixes of all the keywords.

Graph for en, end, endif, do


(start) -> (e id) -> (en id) -> (end keyword) -> (endi id) -> (endif id)
|
|
(d id)
\ for each fail case, id
|
(do keyword)
|
----------------------------------- id
state <- 0
for i <- 1 to n (where n = length of string)
c <- next character of input
state <- T[state, c]
output token corressponding to the final state
--- --# Dynamic dictionary:
Operations on a dictionary: add(word), remove(word), contains(word).
Solution:
Appraoch 1: Hashing was created for this problem.
Other approaches: Trie, FSMs. Better but more complicated.
AGAIN: HASHING WAS MADE FOR THIS.
Using hashing is a strength.
--- --# Breaking into words
Strings: Given a set of words (dictionary), and a set of strings,
write a function that decides if each string can be broken into
substrings that are words in the dictionary. What is a good
implementation of the function?
Solution:
GOODGODTHISPROBLEMISHARD

GOODDEVENISBAD
Approach 1: Trie and simulation of FSM.
G
{
G

O
{
/
GO

O
{
O
GOO

D
{
D
OD
GOOD

D
{
ODD
/
D

A
{
A
DA
/

Y
{
AY
DAY
Y
/
}

Possible words to set elements as null


/ GO GOO GOOD
ODD A AY
/
DAY
Approach 2: Dynamic programming (Similar as above, just a different way of looki
ng at it)
Define A[i]
= True if substring(0..i-1) can be composed with words in dictionary
= False otherwise
Recursive formulation:
A[0] = True
A[i] = `OR over j < i` (A[j] `AND` substring(j..i-1) is a word in the dictionary
)
GOODGODTHISPROBLEMISHARD
ftttftt...
--- --# Set operations
Set operations: Given two linked lists of strings, output a list of
strings that are in both lists (intersection of two unsorted lists).
For size n = 10M, both algos will have roughly same running time
For size n = 1B, hashing will start getting better
Using hashing is a strength.
Approach 1: Sorting
Appraoch 2: Hashing
Running time is proportional to the length of the string (just to check if it ex
ists)
--- --# External problem
Distinct rows: Given a large file (orders of magitude bigger than
available memory), where each line has one or more integers, find the
lines of the file that are distinct. Two lines are considered to be
the same if they contain the same integers (possibly in different
order). For example, "1 2 3 3" is the same as "3 1 3 2". Design an
algorithm that tries to minimize the number of passes over the file.
Appraoch 1:
Make files for all 1s, all 2s etc. Might not work because of filesystem constrai
nts.

Appraoch 2:
Use as hashcode:
* Sum lines
* Number of elements
* Product of numbers (overflow constraints)
* Max, min, median, sum
His answer:
h(Line) -> Index of the hash table
Choose h(x1 x2 ... xn) = h(any permutation of x1 to xn)
ie hash function that is commutative in its arguments
h: Pr(h(X) = h(Y)) = 1/N
such that X != Y
Choose N = size of file/size of memory (ie number of buckets)
Read file: read a line X1..Xn
Compute hn(X1..Xn) = i
Write line to file i
where N = range of h
Each file should fit in memory with high probability
Pass 2: Read each file, remove duplicates, write back to file
--- --# Does a linked list end in a cycle
Fun problem: Does a linked list end in a cycle? Suppose you are given
a singly linked list, where by a programmer error, the last node of
the list may have its next pointer set to an element of the list. The
problem is to find if a given list ends in a cycle or not, in time
O(n) where the list has n nodes, using only O(1) extra space. The
standard solution to this problem uses 2 iterators that run at
different speeds (tortoise and hare solution). Can this problem be
solved with only one iterator?
1.
Tortoise and hare solution.
2.
Assume cycle length "k".
Sum of powers of 2.
k = 1000, for 1024
Loop will hit again with you remembering the 2^cycle-th element.
--- --# Distinct elements
Are all characters in a character array (String in C) distinct? Solve using onl
y O(1) extra space.
Appraoch 1: Bubblesort
Appraoch 2: Heap sort, use array as heap.
Max heap (for ascending order)

A[1..n] -- heap
for i <- 1 to n do
X <- A[1] // max
A[1] <- A[Size]
PercolateDown(1)
A[size+1] <- X
Complexity O(n log n)

Size-// Restore heap

--- --# String: `{a,b,c}*`


String: Given a string as input, find a longest substring that is
composed of at most 3 different characters.
1. Clean solution: Divide and conquer approach:
Divide the string into 2 parts. The string is either in the left, right, or spli
t between the splitting side.
On split, manage:
- Longest suffix with 1 character
- Longest suffix with 2 characters
- Longest suffix with 2 characters
on each side
Crossover: max of cross product of combinations
O(n log n)
2. Fast and dirty solution: Finite state machine approach:
For `i`:
Prob(i) = Longest substring that ends at index `i-1` that has utmost k character
s
|
l

| X |
2 3

Case 1: X belongs to `k` in current solution `Prob(i)`. Extend solution to inclu


de character at index `i`.
Case 2: X is a new character.
| a

b ... a ... c
| d |
rightmost
Bring your marker before the next occurring rightmost element. So bring marker t
o the right of `b`.
Data structure: Balanced binary tree (Tree Map)
O(n log k)
--- --# Recursion: sum of digits
Recursion: Given n, find sum of digits of n mod 10.
Add the digits of n = X
Add the digits of X = X2
:
Till Xn has only one digit.
Solution: Mod each number by 9, sum.
--- ---

# Bitonic arrays
Recursion: Given a bitonic array, find the point of inflection. An
array is bitonic if it is made of a monotonically increasing subarray
that is followed by a decreasing subarray.
Compare mid, mid-1, mid+1.
Case 1: < > - return mid
Case 2: < < - left <- mid or mid + 1
Case 3: > > - right <- mid or mid - 1
Binary search: O(log n)
Variation: for non-increasing, non-decreasing (flat spots)
--- --Number theory:
Determine whether a number is a nontrivial power, n = p^q, (q > 1).
Part 2:
Priority queue seeded with squares.
Output = `<n = p^q, p, q>`
To insert, p^(q+1) if it is less than equal to upper bound
--- --# Subarray with maximum sum
Given an array A[1..n] find a sequence of A with maximum sum (over all subsequen
ces of A)
Solution: Return Sum A[i] if A[i] > 0
What if adjacent elements of the output subsequence must have a difference of mo
re than k (say, k = 5). What if the subsequence must be monotonic?
Solution: Take 6363.
--- --# DP: Submatrix with maximum sum:
DP: Submatrix with maximum sum: Given an MxN array A of numbers, find
a subarray whose sum is a maximum among all subarrays of A.
Method 1:
Easily done in m^2*n^2.
Assume a preprocess step such that:
Output = Sum A[i, j] for i1 <= i <= i2, j1 <= j <= j2.
Calculate prefix sums. Can be done in O(mn).
Calculate a submatrix using inclusion-exclusion:
A4 = (A1 + A2) + (A1 + A3) - A1
1. Here, find prefix sums. O(mn)
2. Compose using above method
for 1 <= i <= i2 <= m

for 1 <= j1 <= j2 <= N do


compute sum
Take max of the above method
Method 2:
Suppose M <= N
for 1 <= i1 <= i2 <= m:
```
i1 ------------|||||||||||
i2 ------------```
= s1 s2 s3 ... sn
Apply 1D algorithm on this approach
--- --# External: substream with `k` different characters
External: Given a (really long) stream of characters, find a shortest
substring that has at least M different characters?
Given array of 0/1, find longest contiguous 1s after flipping up to k 0s into 1s
.
Problem 1:
Same as {a,b,c}* problem conceptually.
Problem 2:

Problem 3:

--- --# DP: Subset sum, Knapsack, Set partition, Balanced set partition.
DP: Subset sum, Knapsack, Set partition, Balanced set partition.
Subset sum: Given a set S of positive numbers and a target t, is there a subset
of S whose sum is t?
Knapsack: Given S and t, find a subset whose sum is largest, but no bigger than
t.
Set partition: Given S, can it be partitioned into two subsets which have equal
sum?
Balanced set partition: Given S, can it be partitioned into two subsets of
equal cardinality and equal sum?
Google question.
15 lines of code
--- --String: Longest substring with no repeating characters.
--- ---

Shortest substring that has the entire alphabet.


Same problem: Smallest subarray of an array that contains all its elements.
--- --# External: `k` largest elements
External problems: k largest elements in a stream. Length of stream
is much bigger than memory, but k is smaller than available memory.
Google:
Keep current `k` largest elements in a min-heap iteratively.
i = k:
Heap of A[1..k]
i = k+1:
A[1] = min element (kth largest element so far)
if A[i] > A[1]
replace A[1] by A[i]
PercolateDown(1)
--- --# Graph number of shortest paths
Find number of shortest paths from source to destination.
(M X N grid)
N(i, j) = N(i - 1, j) + N(i, j - 1)
Top blocked: N(i, j) = N(i - 1, j)
Left blocked: N(i, j) = N(i, j - 1)
Top, left blocked: N(i, j) = 0
--- --# Palindromes and subsequences
Palindromes, subsequences:
Longest palindromic subsequence of a sequence.
Longest subsequence that forms a balanced set of parentheses.
Breaking a string into smallest number of palindromes.
Take 6363.
--- --# DP: Frog crossing river
DP: Frog crossing river: A frog wants to cross a pond of width W. The
frog can jump a maximum distance of D in one jump. Luckily there are
leaves falling from a tree on to the surface of the pond and the frog
can jump on to and from the leaves. A leaf falls every second, and
you are given an array of locations where the leaves are falling.
A[i] = k means, at second i, a leaf lands at a distance of k from the
bank on which the frog is initially located. Find the earliest time
at which the frog is able to cross the pond.
Variations: Leaves stay afloat only for limited time before its surface gets wet

and unsuitable to use as landing pad.


Priority queue of locations a frog can reach at different times.
--- --Simple/Fun: Does a number have rotational symmetry (88,69,000,16191)?
Rotate the number 180 degrees about its centre and you get the same
number.
--- --Trees: Level order traversal of a tree: Given a binary tree as input,
return a list of lists (one list for each level).
--- --DP: Given a grid of numbers. find a path from NW corner to SE corner,
moving only right or down, such that the sum of the numbers on the
path is a maximum. Related problem: How many paths are there with a
given sum K?
--- --No easy answers: Count number of triangles in a graph.
O(d3) is the best solution with a minor improvement.
Just give the O(d3) answer.
--- --2-player coin game: Given a row of coins, with values A[1..n], 2
players play the following game. The players take alternate turns.
At each turn, a player can choose to take a coin at the left end, or a
coin at the right end, or both coins at either end. The game is
played until all coins are taken. What strategy should a player
employ if she wants to maximize the total value of the coins she gets.
--- --# Mnemonics for phone numbers
Given a dictionary of words and a phone number, check if the given
phone number maps to a combination of words from the dictionary.
See your phone for a mapping of each number to letters of the alphabet.
Similar to checking if a string is composed of words.
--- --# Tree traversal
Tree traversal: Reconstruct binary tree from its inorder, and postorder travers
als.
What if the elements are not distinct?

Well known problem for practicing recursion.


Left subtree and right subtree from the inorder in the postorder's last element
(root).
--- --Group interval scheduling: Given groups of intervals, G_1..G_k, where
each group has 2 intervals, check if there is a collection of k
mutually disjoint intervals, that consists of one interval from each
group.
--- --# Offline stock market
Off-line stock market: Given an initial budget, and an array of stock
prices over n days, find buy/sell transactions to maximize net worth
on day n.
Gets more complex with multiple stocks.
In the given case only consider inflection points.
Buy low, sell high.
--- --# String: Number of distinct substrings
Strings: Find the number of distinct substrings of a given string.
Longest repeating prefix: Find longest prefix p of a string which has pp as a pr
efix.
Suffix trees
--- --# Heuristics
Heuristics:
Friend recommendation in Social networks.
--- --# String: Extending to a palindrome
Shortest string that can be added as a prefix (or suffix) to a given string to m
ake it a palindrome.
--- --https://en.wikipedia.org/wiki/Longest_palindromic_substring
https://en.wikipedia.org/wiki/Maximum_subarray_problem

Você também pode gostar