useful code Flashcards

1
Q

Sort an array of 0s, 1s and 2s

A

in general if you know the number in the array just count them and then print them in order. Think about the Counting Sort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is jump search?

A

Just instead of doing binary search you jump linearly from 0 to m to 2m ….. when you get somethign higher than x you stop and you do linear search between nm and (n+1)m.

Time complexity is O(√ n) between linear and binary search.

Like in the EGG from skyscraper problem.

Binary Search is better than Jump Search, but Jump search has an advantage that we traverse back only once (Binary Search may require up to O(Log n) jumps,

So in a system where jumping back is costly, we use Jump Search.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you check if 2 elemetns of the array have products equal to p.

A

O(n^2) of course do the naive thing of tring all the products.

O(nlogn): you can sort and then go to the array O(n) and search for prod/arr[i] in the rest of the array. This give you O(nlogn)

As usual hash are amazingly good. buit a hash in O(n) than look for p-1 p/2-2 etch if you find both you are done.

def find_prod(A,prod):
freq = [0]*(prod+1)
for a in A:
if a freq[a] = 1
i=1
j=prod
while i # print(i,j)
if freq[i] and freq[j]:
print(i,j)
return True
i+=1
if j%i !=0:
continue
else:
j = prod//i
return False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Sort a nearly sorted (or K sorted) array

Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time.

A

We can use Insertion Sort to sort the elements efficiently. Following is the C code for standard Insertion Sort.

The inner loop will run at most k times. To move every element to its correct place, at most k elements need to be moved. So overall complexity will be O(nk)

We can sort such arrays more efficiently with the help of Heap data structure. Following is the detailed process that uses Heap.

1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time (See this GFact)
2) One by one remove min element from heap, put it in result array, and add a new element to heap from remaining elements.

Removing an element and adding a new element to min heap will take Logk time. So overall complexity will be O(k) + O((n-k)*logK)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Find subarray with given sum.

A

Again brute force is O(n^2). The key is to understand that once your sum exceeds the value you are looking for you just have to remove elements starting from the beginning till you get to exactly or below the value you are looking for. def subArraySum(arr, n, sum): for i in range(n): curr_sum = arr[i] j = i+1 while j <= n: if curr_sum == sum: print (“Sum found between”) print(“indexes %d and %d”%( i, j-1)) return 1 if curr_sum > sum or j == n: break curr_sum = curr_sum + arr[j] j += 1 print (“No subarray found”) return 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to identify is a problem is a dynamic programming one?

A

Typically, all the problems that require to maximize or minimize certain quantity or counting problems that say to count the arrangements under certain condition or certain probability problems can be solved by using Dynamic Programming.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can you check if 2 number are missing from a sequence?

A

In this case, xor or the sum trick might not be that convenience. If you can leave with the O(n) space you can build a hash table.

if you use the sum you get the sum of the 2 numbers. You can get the average. one is going to be smaller than that one higher. You can repeat the sum trick for 1-avg avg-n to find out the 2 numbers.

With xor, it is the same you get x^y where xy are missing.

now if you have a bit 1 in that, it means that either x or y do not have that. Select all the elements with 1 there and do a xor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.

A

O(n) and space efficient We create a Dequeue, Qi of capacity k, that stores only useful elements of current window of k elements. An element is useful if it is in current window and is greater than all other elements on left side of it in current window. We process all array elements one by one and maintain Qi to contain useful elements of current window and these useful elements are maintained in sorted order. The element at front of the Qi is the largest and element at rear of Qi is the smallest of current window. Thanks to Aashish for suggesting this method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Find the recursion for the cutting rod problem

Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)

length | 1 2 3 4 5 6 7 8 ——————————————– price | 1 5 8 9 10 17 17 20

A

We can get the best price by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.

Let cutRod(n) be the required (best possible price) value for a rod of length n. cutRod(n) can be written as following.

cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}

Returns the best obtainable price for a rod of length n and

price[] as prices of different pieces

def cutRod(price, n):

val = [0 for x in range(n+1)]

val[0] = 0

Build the table val[] in bottom up manner and return

the last entry from the table

for i in range(1, n+1):

max_val = INT_MIN

for j in range(i):

max_val = max(max_val, price[j] + val[i-j-1])

val[i] = max_val

return val[n]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which sorting algorithms in its typical implementation gives the best performance when applied on an array which is sorted or almost sorted

A

Insertion sort takes linear time when input array is sorted or almost sorted (maximum 1 or 2 elements are misplaced). All other sorting algorithms mentioned above will take more than linear time in their typical implementation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains 3 lines . The first line contains 3 space separated integers N, M, X. Then in the next two lines are space separated values of the array A and B respectively.

Input

s =9
A = 1 2 4 5 7
B = 5 6 3 4 8

Output

1 8, 4 5, 5 4

A

If you have space hashing would work

def find_pairs(A,B,s):
freq = [0]*200
for i in range(0,len(B)):
freq[s-B[i]] = 1
for i in range(0,len(A)):
if freq[A[i]] == 1 :
print(A[i],s-A[i])
return 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the output of the following program :

print 0.1 + 0.2 == 0.3

A

Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off errors from 0.1 and 0.2 accumulate and hence there is a difference of 5.5511e-17 between (0.1 + 0.2) and 0.3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Find if a string is a permutatin of a palindrom!

A

They key here is to see that to be a palindrome you need to have an even frequency for each character but one in odd strings (that can be the central). Then just implement this with an hash!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Decode the string

An encoded string (s) is given, the task is to decode it.

The pattern in which the strings were encoded were as follows

original string: abbbababbbababbbab
encoded string : “3[a3[b]1[ab]]”.

A

The idea is to use two stacks, one for integers and another for characters.
Now, traverse the string,

Whenever we encounter any number, push it into the integer stack and in case of an alphabet (a to z) or open bracket (‘[‘), push it onto the character stack.

Whenever any close bracket (‘]’) is encounter pop the character from the character stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack.

def decode_str(s):
string = list(s)
stack_chr = []
stack_int = []
for i in string:
if i.isdigit():
stack_int.append(int(i))
elif i != “]”:
stack_chr.append(i)
elif i == “]”:
_n = stack_int.pop()
_chr = stack_chr.pop()
_str = []

while _chr != “[”:
_str.append(_chr)
_chr = stack_chr.pop()

stack_chr.append(““.join(_str) * _n)
else:
return 0

return ““.join(stack_chr)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Interpolation search?

A

It is a binary search where you do not look in the middle.

you choose where to look by comparing x with the highest and smallest elements in the array.

pos = lo + [(x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

You need to do this in place.

Note that if you end up using an additional array, you will only receive partial score.

Example:

If the array is

1 2 3 4 5 6 7 8 9

Then the rotated array becomes:

7 4 1 8 5 2 9 6 3

A

Below are some important observations.

First row of source –> First column of destination, elements filled in opposite order

Second row of source –> Second column of destination, elements filled in opposite order

so … on

Last row of source –> Last column of destination, elements filled in opposite order.

An N x N matrix will have floor(N/2) square cycles. For example, a 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row and 1st column. The second cycle is formed by 2nd row, second-last column, second-last row and 2nd column.

The idea is for each square cycle, we swap the elements involved with the corresponding cell in the matrix in anti-clockwise direction i.e. from top to left, left to bottom, bottom to right and from right to top one at a time. We use nothing but a temporary variable to achieve this.

An Inplace function to rotate

N x N matrix by 90 degrees in

anti-clockwise direction

def rotateMatrix(mat):

Consider all squares one by one

for x in range(0, int(N/2)):

Consider elements in group

of 4 in current square

for y in range(x, N-x-1):

store current cell in temp variable

temp = mat[x][y]

move values from right to top

mat[x][y] = mat[y][N-1-x]

move values from bottom to right

mat[y][N-1-x] = mat[N-1-x][N-1-y]

move values from left to bottom

mat[N-1-x][N-1-y] = mat[N-1-y][x]

assign temp to left

mat[N-1-y][x] = temp

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Find the first unique element of a string!

A

You go through the string, build a hash table with the frequency, then you go trough the string again and you stop when freq[char] ==1

This is an O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Search an element in a sorted rotated array.

Like this?

5 6 7 8 9 10 1 2 3

Also what is a condition to be able to do this in log(n)?

A

low + (high - low)/2;

You need to have no repeated elements. Otherwise, you can not do this in O(logn):

Otherwise, you can obtain the pivot, using a binary search slightly modified in logN. Once you have the pivot you can do a bnary search in one of the 2 arrays in the usual way.

In the same way you can get the minimum value

def findPivot(arr, low, high):

base cases

if high < low:

return -1

if high == low:

return low

mid = int((low + high)/2)

if mid < high and arr[mid] > arr[mid + 1]:

return mid

if mid > low and arr[mid] < arr[mid - 1]:

return (mid-1)

if arr[low] >= arr[mid]:

return findPivot(arr, low, mid-1)

return findPivot(arr, mid + 1, high)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Recursion for friends pairing problem

Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up.

A

f(n) = ways n people can remain single or pair up.

For n-th person there are two choices:

1) n-th person remains single, we recur for f(n - 1)
2) n-th person pairs up with any of the remaining n - 1 persons.We get (n - 1) * f(n - 2)

Therefore we can recursively write f(n) as: f(n) = f(n - 1) + (n - 1) * f(n - 2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Find the recursion for the tiling problem

Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to tile the given board using the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile.

A

Let “count(n)” be the count of ways to place tiles on a “2 x n” grid, we have following two ways to place first tile.

1) If we place first tile vertically, the problem reduces to “count(n-1)”
2) If we place first tile horizontally, we have to place second tile also horizontally. So the problem reduces to “count(n-2)”

Therefore, count(n) can be written as below.

count(n) = n if n = 1 or n = 2 count(n) = count(n-1) + count(n-2)

This is basically a fibonacci series and it can be solved in the same way

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.

A

The idea is to get total sum of array first. Then Iterate through the array and keep updating the left sum which is initialized as zero. In the loop, we can get right sum by subtracting the elements one by one. Thanks to Sambasiva for suggesting this solution and providing code for this. 1) Initialize leftsum as 0 2) Get the total sum of the array as sum 3) Iterate through the array and for each index i, do following. a) Update sum to get the right sum. sum = sum - arr[i] // sum is now right sum b) If leftsum is equal to sum, then return current index. c) leftsum = leftsum + arr[i] // update leftsum for next iteration. 4) return -1 // If we come out of loop without returning then // there is no equilibrium index

22
Q

Given an array check in O(n) if there are 2 elements with a given sum

A

You can do some linear sorting like insertion sort and then move to indeces from left and right of an array.

The best way I think is too build an hash table with sum-A[i] and cycle over A[i], it has a bit of space complexity but it is O(n)

def find\_sum\_3(A, sum\_in):
 freq = [0]\*1000

for i in range(len(A)):
if freq[A[i]] ==1:
return True
else:
if sum_in -A[i]>0:
freq[sum_in - A[i]] = 1
return False

23
Q

Find if two string is the permutation of the other?

A

Create an hash table again and check. I think you can also use an xor fingerprint to be O(1) in space but that will tell you if they are not a permutation not if they are. As usual for this kind of thing sorting is cleaner but slower O(n logn).

24
Q

How would you compute binomial coefficient?

A

first try to find the relation

C(n,k) = C(n-1,k-1) + C(n-1,k)

Then you dynamical programming. If you do not want to have to store a matrix think about the pascal coeff in binomial (basically you just keep one row of the matrix)

1

11

121

1331

25
Q

Given an array A [] having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1

A

Naive O(n^2)

1) Push the first element to stack.
2) Pick rest of the elements one by one and follow following steps in loop.
….a) Mark the current element as next.
….b) If stack is not empty, then pop an element from stack and compare it with next.
….c) If next is greater than the popped element, then next is the next greater element for the popped element.
….d) Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements
3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.

def printNGE(arr):

s = createStack()

element = 0

next = 0

push the first element to stack

push(s, arr[0])

iterate for rest of the elements

for i in range(1, len(arr), 1):

next = arr[i]

if isEmpty(s) == False:

if stack is not empty, then pop an element from stack

element = pop(s)

’'’If the popped element is smaller than next, then

a) print the pair
b) keep popping while elements are smaller and

stack is not empty ‘’’

while element < next :

print(str(element)+ “ – “ + str(next))

if isEmpty(s) == True :

break

element = pop(s)

’'’If element is greater than next, then push

the element back ‘’’

if element > next:

push(s, element)

’'’push next to stack so that we can find

next greater for it ‘’’

push(s, next)

’'’After iterating over the loop, the remaining

elements in stack do not have the next greater

element, so print -1 for them ‘’’

while isEmpty(s) == False:

element = pop(s)

next = -1

print(str(element) + “ – “ + str(next))

26
Q

Lower bound for comparison based sorting algorithms?

A

nlogn

You can see that by building a binary tree (which is what doing comparison actually is.)

27
Q

Given an array arr[], find the maximum j – i such that arr[j] > arr[i]

Input: {34, 8, 10, 3, 2, 80, 30, 33, 1} Output: 6 (j = 7, i = 1) Input: {9, 2, 3, 4, 5, 6, 7, 8, 18, 0} Output: 8 ( j = 8, i = 0) Input: {1, 2, 3, 4, 5, 6} Output: 5 (j = 5, i = 0) Input: {6, 5, 4, 3, 2, 1} Output: -1

A

The not efficient way is to do 2 loops the external from the left of the array and the internal from the right.

The efficient way is as always to keep the relevant information you get from swiping the array. Having an array min[i] with the minimum value on the left of i and max[j] with maximum value on the right of the position j of the array.

Then you do similar to merge sort:

i = 0, j = 0, maxDiff = -1;

while (j < n && i < n)

{

if (LMin[i] < RMax[j])

{

maxDiff = max(maxDiff, j-i);

j = j + 1;

}

else

i = i+1;

}

28
Q

Find the recursion for the painting fence algorithm:

Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color.

A

f(n) = f(n)*k - F(n-3)*(k-1)

This is all the possibilities minus the one not allowed cause they would have 3 similar colors together.

29
Q

Reverse words in a given string

Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”

A

It is quite simple. One cool trick to remember is that you can:

Reverse the individual words, we get the below string. “i ekil siht margorp yrev hcum” 2) Reverse the whole string from start to end and you get the desired output. “much very program this like i”

You can reverse a string with s[::-1]

30
Q

Think about the recursion relation for the choice area problem:

Consider a game, in which you have two types of powers, A and B and there are 3 types of Areas X, Y and Z. Every second you have to switch between these areas, each area has specific properties by which your power A and power B increase or decrease. We need to keep choosing areas in such a way that our survival time is maximized. Survival time ends when any of the powers, A or B reaches less than 0.

A

The idea is similar to the coins change problem. It can be solved recursively, splitting among the 3 possible areas you can substract (there it was the different coins). Of course this is exponential. You can use a hashtable to memorize this.

maxSurvival(A, B, X, Y, Z, last, memo):

if any of A or B is less than 0, return 0

if (A <= 0 or B <= 0):

return 0

cur = area(A, B)

if already calculated, return calculated value

for ele in memo.keys():

if (cur.a == ele.a and cur.b == ele.b):

return memo[ele]

step to areas on basis of last chosen area

if (last == 1):

temp = 1 + max(maxSurvival(A + Y.a, B + Y.b,

X, Y, Z, 2, memo),

maxSurvival(A + Z.a, B + Z.b,

X, Y, Z, 3, memo))

elif (last == 2):

temp = 1 + max(maxSurvival(A + X.a, B + X.b,

X, Y, Z, 1, memo),

maxSurvival(A + Z.a, B + Z.b,

X, Y, Z, 3, memo))

elif (last == 3):

temp = 1 + max(maxSurvival(A + X.a, B + X.b,

X, Y, Z, 1, memo),

maxSurvival(A + Y.a, B + Y.b,

X, Y, Z, 2, memo))

31
Q

Next Greater Element

Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1.

For the input array [4, 5, 2, 25},

Element NGE 4 –> 5 5 –> 25 2 –> 25 25 –> -1

A

You can do a O(n^2) simple 2 loops. Or

you use a stack and you get O(n).

The idea is pop the first then if smaller than the last element of the stack you append. Else you remove from th stack (the one you are considering will be the NGE) and you keep popping till you get something greater than the one under consideration. At that point you stash.

def next_gret(a):
stack = []
out = [-1] * len(a)
stack.append((a[0], 0))
for i in range(1, len(a)):
while bool(stack)==True:
elem = stack.pop()

if a[i] > elem[0]:
out[elem[1]] = a[i]

stack.append((a[i],i))
else:
stack.append(elem)
stack.append((a[i], i))
break
if bool(stack)==False:
stack.append((a[i], i))

return out

32
Q

Converting Roman Numerals to Decimal lying between 1 to 3999

Given a Romal numeral, find its corresponding decimal value.

Input : IX Output : 9 Input : XL Output : 40 Input : MCMIV Output : 1904 M is a thousand, CM is nine hundred and IV is four

A

Algorithm to convert Roman Numerals to Integer Number :

Split the Roman Numeral string into Roman Symbols (character).

Convert each symbol of Roman Numerals into the value it represents.

Take symbol one by one from starting from index 0:

If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total.

else subtract this value by adding the value of next symbol to the running total.

33
Q

How do you get the minimum value in a sorted rotated array?

A

low + (high - low)/2;

You need to have no repeated elements. Otherwise, you can not do this in O(logn):

Otherwise, you can do like in doing a search in a rotated array obtain the pivot, using a binary search slightly modified in logN. Once you have the pivot you can do a binary search in one of the 2 arrays in the usual way.

In the same way you can get the minimum value

def findPivot(arr, low, high):

base cases

if high < low:

return -1

if high == low:

return low

mid = int((low + high)/2)

if mid < high and arr[mid] > arr[mid + 1]:

return mid

if mid > low and arr[mid] < arr[mid - 1]:

return (mid-1)

if arr[low] >= arr[mid]:

return findPivot(arr, low, mid-1)

return findPivot(arr, mid + 1, high)

34
Q

Think and write a recursive solution and a dynamical programming one for the Fibonacci series?

A

Recursive

def Fibonacci(n):

if n<0:

print(“Incorrect input”)

First Fibonacci number is 0

elif n==1:

return 0

Second Fibonacci number is 1

elif n==2:

return 1

else:

return Fibonacci(n-1)+Fibonacci(n-2)

Dynamical

def fibonacci(n):

a = 0

b = 1

if n < 0:

print(“Incorrect input”)

elif n == 0:

return a

elif n == 1:

return b

else:

for i in range(2,n):

c = a + b

a = b

b = c

return b

35
Q

How can you find elements that does not appear in an array?

A

you can use the sum formula well start from 0, xor all the number from 1 to len(A) and use the xor trick to get odd elements

36
Q

Smallest subarray with a sum greater than a given value.

Given an array of integers and a number x, find the smallest subarray with sum greater than the given value.

Examples: arr[] = {1, 4, 45, 6, 0, 19} x = 51 Output: 3 Minimum length subarray is {4, 45, 6} arr[] = {1, 10, 5, 2, 7} x = 9 Output: 1 Minimum length subarray is {10}

A

Brute force O(n^2)

A simple solution is to use two nested loops. The outer loop picks a starting element, the inner a considers all elements (on right side of current start) as ending element. Whenever sum of elements between current start and end becomes more than the given number, update the result if current length is smaller than the smallest length so far.

O(N) solutions

use a sliding window. Keep adding when you get bigger remove from the beginning

Initialize minLength = length of the array and say the given integer is x.

Take variables currSum = 0, start = 0

Do the linear scan in array and start adding each element to the currSum.

if currSum > x then start subtracting element from the start.(currSum-arrA[start]) check the length of the subarray, if it is less then the minLength (currentIndex-start<minlength>
</minlength>

37
Q

Find the first bit = 1 in a binary representation

A

You have to go brute force. Cycle trough it with a mask

def find\_bit(n):
 for i in range(len(bin(n))):
 if (1\< return i
 return 0
38
Q

Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum.

A

Brute force is O(n^2) the key here is to see that you can actually reuse the value of the maximum substring that ends at index n, then you compare max+n with n itself and that is the new max string ending here. You return the global max int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far;

39
Q

Replace some element of a string with something else like white space with %20 (urlify)?

A

You can just go through the string and count white space. Then you know the new lenght (since “ “ and %20 have different lenght). If you have to modify a string YOUSHOULD GO FROM THE END!! so that you have a buffer and not caring about over writing. If you can create a new string it is even easier it is a O(N) not 2N operation.

40
Q

Count number of ways to partition a set into k subsets

Given two numbers n and k where n represents number of elements in a set, find number of ways to partition the set into k subsets.

find the recursion series and think about a dynamic implementation

A

When we add a (n+1)’th element to k partitions, there are two possibilities.

1) It is added as a single element set to existing partitions, i.e, S(n, k-1)
2) It is added to all sets of every partition, i.e., k*S(n, k)

Therefore S(n+1, k) = k*S(n, k) + S(n, k-1) which means S(n, k) = k*S(n-1, k) + S(n-1, k-1)

// Returns count of different partitions of n

// elements in k subsets

int countP(int n, int k)

{

// Table to store results of subproblems

int dp[n+1][k+1];

// Base cases

for (int i=0; i<=n; i++)

dp[i][0] = 0;

for (int i=0; i<=k; i++)

dp[0][k] = 0;

// Fill rest of the entries in dp[][]

// in bottom up manner

for (int i=1; i<=n; i++)

for (int j=1; j<=i; j++)

if (j == 1 || i == j)

dp[i][j] = 1;

else

dp[i][j] = j*dp[i-1][j] + dp[i-1][j-1];

return dp[n][k];

Time complexity is O(nk) it is basically equal to the element of the matrix.

41
Q

How can you find elements that happen in an array on an odd number of time?

A

Simply xor all the number a xor a = 0 a xor a xor x = x Only the odd one is left!

42
Q

Given a String of length N reverse the whole string without reversing the individual words in it. Words are separated by dots.

i. like.this.program.very.much
- ->

much.very.program.this.like.i

A

It is O(n) and quite simple. Just go through the string and reverse. One cool idea is to reverse each word at the first pass (much –> hcum) and then reverse the entire string

43
Q

How does binary search work? how need the array to be?

What if you are looking for a position present multiple times?

A

The array needs to be sorted.

  • Compare x with the middle element.
  • If x matches with the middle element, we return the mid index.
  • Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.
  • Else (x is smaller) recur for the left half.

If many instances of x are present you remember the poistion and you do a binary search on the left.

44
Q

How to check if string only contains unique elements? what if you want to do this in O(1) time

A
  • Build an hash table of lengh the total number of chars - Use set() -use python counter You can sort and check for consecutive items if you need O(1) space
45
Q

Given an expression string exp, examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.

A

1.Push the element into the stack . 2.Pop the element from the stack if the top of stack has the opposite parenthesis. 3. Finally , if the stack size is empty at the end . The answer is balanced else it is unbalanced .

46
Q

How to write an efficient method to calculate x raise to the power n?

A

you can use divide and conquer for this too and manage to do this in log(n)

def power(x, y):

if (y == 0): return 1

elif (int(y % 2) == 0):

return (power(x, int(y / 2)) *

power(x, int(y / 2)))

else:

return (x * power(x, int(y / 2)) *

power(x, int(y / 2)))

47
Q

A bitonic array A Bitonic Sequence is a sequence of numbers which is first strictly increasing then after a point strictly decreasing. How do you search in something like this?

A

Again this is basically a sorted rotated array.

You find the bitonic point then you have 2 sorted arrays. I think it is easy to find the maximum in one pass but to find the minimum you need to find bitonic point.

48
Q

3 ways to reverse a string in python!

A

class Solution(object): def reverseString(self, s): l = len(s) if l < 2: return s return self.reverseString(s[l/2:]) + self.reverseString(s[:l/2]) class SolutionClassic(object): def reverseString(self, s): r = list(s) i, j = 0, len(r) - 1 while i < j: r[i], r[j] = r[j], r[i] i += 1 j -= 1 return ““.join(r) class SolutionPythonic(object): def reverseString(self, s): return s[::-1]

49
Q

Find minimum number of coins that make a given value

Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm} valued coins, what is the minimum number of coins to make the change?

A

This problem is a variation of the problem discussed Coin Change Problem. Here instead of finding total number of possible solutions, we need to find the solution with minimum number of coins.

The minimum number of coins for a value V can be computed using below recursive formula.

If V == 0, then 0 coins required.

If V > 0

minCoin(coins[0..m-1], V) = min {1 + minCoins(V-coin[i])} where i varies from 0 to m-1 and coin[i] <= V

def minCoins(coins, m, V):

base case

if (V == 0):

return 0

Initialize result

res = sys.maxsize

Try every coin that has smaller value than V

for i in range(0, m):

if (coins[i] <= V):

sub_res = minCoins(coins, m, V-coins[i])

Check for INT_MAX to avoid overflow and see if

result can minimized

if (sub_res != sys.maxsize and sub_res + 1 < res):

res = sub_res + 1

return res

50
Q

Longest Increasing Subsequence (hard)

Given a sequence, find the length of the longest increasing subsequence from a given sequence .

This subsequence is not necessarily contiguous, or unique.

For example:
length of LIS for
{ 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6 and LIS is {10, 22, 33, 50, 60, 80}.

A

For this you need a recursive algorithm:

Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS.
Then, L(i) can be recursively written as:
L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or
L(i) = 1, if no such j exists.
To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n.
Thus, we see the LIS problem satisfies the optimal substructure property as the main problem can be solved using solutions to subproblems.

def _lis(arr , n ):

to allow the access of global variable

global maximum

Base Case

if n == 1 :

return 1

maxEndingHere is the length of LIS ending with arr[n-1]

maxEndingHere = 1

”"”Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]

IF arr[n-1] is maller than arr[n-1], and max ending with

arr[n-1] needs to be updated, then update it”””

for i in xrange(1, n):

res = _lis(arr , i)

if arr[i-1] < arr[n-1] and res+1 > maxEndingHere:

maxEndingHere = res +1

Compare maxEndingHere with overall maximum. And

update the overall maximum if needed

maximum = max(maximum , maxEndingHere)

51
Q

Count the triplets

Given an array of distinct integers. The task is to count all the triplets such that sum of two elements equals the third element.

A

Simple solution is O(N^3)

Sort the given array first.

Start fixing the greatest element of three from back and traverse the array to find other two numbers which sum upto the third element.

Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers

O(N^2)

You can probably also create an hash table with all the sums. This is also O(N^2) it takes more memory though

52
Q

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

A

Use the array itself as an hash table.

class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
output = []
for num in nums:
nums[abs(num)-1] = -abs(nums[abs(num)-1])
for i in range(len(nums)):
if nums[i] > 0:
output.append(i+1)

return output