Professional Documents
Culture Documents
Balaji Problem Solving
Balaji Problem Solving
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.
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
/
}
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)
| X |
2 3
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
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.
--- ---