Arrays Flashcards

1
Q

Rain Water Trapped

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.

A

We keep two arrays.
Array 1 with list of Max Height on Left of an Index.
Array 2 with list of Max Height on Right of an Index.
For each index, water will fill upto
minOfHeight(Left,Right)
We subtract the height of building on this index from the value obtained

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

You are given an array of N integers, A1, A2, …. AN.

Return the maximum value of f(i, j) for all 1 ≤ i, j ≤ N. f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.

A

We will make an assumption here that i will always be greater than j.
So |i-j| = i-j
|A[i] - A[j]| + i - j can be written in two possible ways, one of which will be our answer
A[i] - A[j] + i - j
(A[i]+i) - (A[j]+j) => F(i) - F(j) where F(n)= A[n]+n
OR
A[j] - A[i] + i - j
(A[j] - j) - (A[i]-i) => F(a) - F(b) where G(n) = A[n]-n

To Maximize above values we need to find values of n such that
Max(F(n)) - Min(F(n))
Max(G(n)) - Min(G(n))
ie
we need to find 4 variables: Max1,Min1, Max2, Min2
and just return the Max of (Max1-Min1, Max2-Min2)

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

Maximum Consecutive Gap

Given an unsorted integer array A of size N.
Find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.
Eg 1 10 5 sorted will be 1 5 10
and max gap will be 5

A

We can’t sort entire array.
Lets start by finding the minimum possible value of our answer.
ie Min value of Maximum Gap will be the one in best case where every no is separated with the same gap
eg 1234 or 2468 10
Value of such a gap will be (MaxVal -MinVal)/noOFGaps
ie (4-1)/3 and (10-2)/4=> 1 & 2
now we create an array of these gaps storing the min and max value of each gap in every bucket
No of buckets will be Ceiling of (Entire Range Values)/gapSize
(max-min+1)/gapsize=> 4, 5

So we don’t need to calculate for values lying in our buckets.
we will fill these bucket array and subtract
the Max of a Left Bucket with min of Right Adjacent Bucket with values.

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

Carotenemia

You are given an Array of boxes A, where each box consists of oranges. You want to eat atleast B oranges. You start from the 0th index of the array, and keep eating oranges until you eat B oranges. If oranges from a box at ith index get depleted, you start eating from the (i+1)th box.

Determine index of the box where you finish eating B number of oranges. If you don’t eat B oranges even after eating from all the boxes, return -1.

A

We just keep reducing the value of B with array A values while traversing through it untill B is 0 or complete traversal.

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

Spiral Order Matrix II
Given an integer A, generate a square matrix filled with elements from 1 to A2 in spiral order.

Input:  4
Output:
        [1, 2, 3, 4],
        [12, 13, 14, 5],
        [11, 16, 15, 6],
        [10, 9, 8, 7]
A

We keep 4 variables Top,Left,Right and Bottom

For every iteration
We do 4 steps

Fill Top Row till Right Reached and update Top Value
Fill Right Column till Bottom Reached and update Right
Fill Bottom Row till Left Reached and Update Left
Fill Left Column till Top Reached and Update Left

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
Set Matrix Zeros
Update entire row and column of a 0 cell with 0.
Input :
       [1, 0, 1],
        [1, 1, 1],
        [1, 0, 1]   

Output 2:
[0, 0, 0],
[1, 0, 1],
[0, 0, 0]

A

Approach 1 is keep row and column values to update in two hashsets
And just traverse through entire 2d array check if its row or column lies in these stored values and update to 0.

Approach 2 when no extra space is Allowed
For each zero, we traverse through entire row and column of it and update the values to negative.
And in the end through entire matrix to replace negative values with 0’s

Approach 3 is we update the first row and first column with -1 which will mean that we have to update entire/row or column with 0
But for cell 0,0 we can keep 3 states
update row only
update column only
or update both based on the -ve value stored.

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

Implement the next permutation, which rearranges numbers into the numerically next greater permutation of numbers for a given array A of size N.

If such arrangement is not possible, it must be rearranged as the lowest possible order i.e., sorted in an ascending order.

Eg for input
123
132 will be OP

A

We traverse from right and keep comparing last two values
As soon as the Left Value is Smaller than the right one
we stop

1 2 3 6 5 4
Eg 3 & 6 here
So indexToReplace will be 3

We replace it with the just larger value on the right
which is 4
so it becomes
124653
but still its not the next permutation
We just reverse the rest array
124356

Eg 2:
123564>123654>123645

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

Reading Newspaper
You have a newspaper which has A lines to read.

You decided to start reading the 1st line from Monday. You are given a schedule, B, where B[i] = number of lines you can read on that day.

You are very strict in reading the newspaper and you will read as much as you can every day.

Determine and return, which day of the week you will read the last line of the newspaper.

A

We just keep reducing A till it is 0 while traversing through B
And return the day index at the end.

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

Sum of All Sub Matrices

Given a 2D Matrix A of dimensions N*N, we need to return sum of all possible submatrices.
1 2
3 4
So sum of all these values
1,
2,
3,
4
12
13
34
24
1234
Output: 40
A

We can’t just find out every submatix and then add.

Instead we try to find out the no of sub matrices Count every element x will fall into.
So for every element sum will be x*Count

Count can be easily determined using its row column values i,j

For Top Left => (i+1)(j+1)
For Bottom Right => (N-i)
(N-j)
Total Count => (i+1)(j+1)(N-1)*(N-j)

for eg
12
34
we get count for each as 2*2*1*1=>4
4*1+4*1+4*3+4*4
40
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Merge Intervals

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,9].

Example 2:

Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] would result in [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

Make sure the returned intervals are also sorted.

A

Its not that hard.
We create methods to check whether intervals overlap
ie !(a.start>b.end || b.start>a.end);
one to merge two intervals, and one to check which interval is greater

We create an output array
and intitalize mergeInterval with newInterval values.

We traverse through initial array and keep merging the mergeinterval if it overlaps
If it doesn’t we add the mergedInterval and set mergedInterval to the new one.

In the end we compare mergedInterval and last one to check which is greater and add them in proper order.

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

Flip

You are given a binary string A(i.e. with characters 0 and 1) consisting of characters A1, A2, …, AN. In a single operation, you can choose two indices L and R such that 1 ≤ L ≤ R ≤ N and flip the characters AL, AL+1, …, AR. By flipping, we mean change character 0 to 1 and vice-versa.

Your aim is to perform ATMOST one operation such that in final string number of 1s is maximised.

If you don’t want to perform the operation, return an empty array. Else, return an array consisting of two elements denoting L and R. If there are multiple solutions, return the lexicographically smallest pair of L and R.

A

Initialize two variables L and R as -1
and one variable tempL
Also store values of diffCurr and diffMax
ie add +1 for every 0, and -1 for every 1

while traversing

if diffCurr becomes less than zero
set value of tempL to i+1
and reset diffCur to 0

if diffCur becomes greater than diffMax
set diffMax to diffCur
L to tempL
R to i

If L is still -1 return Blank
otherwise return values of L and R

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

Special Subsequences “AG”

You have given a string A having Uppercase English letters.

You have to find that how many times subsequence "AG" is there in the given string.
Eg
A = "ABCGAG"
output 3
2 G after first A
1 G after second A
A

Just keep the value of count of ‘A’ while traversing through the string.

As soon as a G is found
add this value to total Sum.

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

First Missing Integer
Given an unsorted integer array A of size N. Find the first missing positive integer.

Note: Your algorithm should run in O(n) time and use constant space.

Inputs

[1, 2, 0]
[3, 4, -1, 1]
[-8, -7, -6]

Outputs
3
2
1

A

Max value of our answer can be the count of our array.

So let’s just create a new array with same size or use the initial one itself.
We will store i at A[i] while traversing through the array

Using same array we ignore if A[i]=i
else we put value of A[i] at A[A[i]]
and value of A[A[i]] at A[i]
and process i again.

In the end we traverse through the final array to check where A[i]= i

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

Merge Overlapping Intervals

Given a collection of intervals, merge all overlapping intervals.

A

We just sort the array first and then use same technique to merge as in similar question

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

Minimum swaps required to bring all elements less than or equal to k together

Given an array of integers A and an integer B, find and return the minimum number of swaps required to bring all the numbers less than or equal to B together.
Any 2 no’s can be swapped.

Input 1:
A = [1, 12, 10, 3, 14, 10, 5]
B = 8

Input 2:
A = [5, 17, 100, 11]
B = 20

Output 1: 2
Output 2: 1

A

Traverse through the array and find the no of items to be put together, ie count of all items less than B

Lets call this teamCount

traverse from 0 to teamCount

We need to find the range of an L to TeamCount
where the outliers are minimum

Eg: Input 1 for B=8
1,12,10,3,14,10,5
Team Count=3

from index 0 to 2
outliers are 2
from 1 to 3, we just check 0 and 3 and update outlier count
its still 2
from 2 to 4
its 2
till end its 2
so our output is 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Minimum number of jumps to reach end.

Given an array of non-negative integers A where each element represents your maximum jump length at that position.
The initial position is the first index of the array and goal is to reach the last index of the array with the minimum number of jumps.

Example Inputs:
A = [1, 2, 3, 4, 5]
A = [5, 17, 100, 11]

Outputs
3
1

A

We will use the concept of steps and ladders here.
Initialize jumps as 1 as at least 1 jump is required.

Keep 2 variables,
CouldReachUpto=> This will store the maximum value we could reach up to. If we made the jump.

We update this value at every iteration by keeping maximum value between current value and currentPos+valueAtCurrentPos

NoOfStepsLeft=> No of steps we can walk from one point.

As we need to find best possible solution we will keep on walking every step and reduce value from noOfStepsLeft

As soon as this becomes 0 (It means we’ve reached the maxAttainablePos too)
We do jumps++
and update its value to maxReachablePos-currentPos

17
Q

Add One To Number

Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ).

Inputs
[1,2,3]
[8.9.9]
[9,9,9]
Output
[1,2,4]
[9,0,0]
[1,0,0,0]
A

Simple
we just do reverse traversal from lastIndex
and check if value is 9
if its 9 we convert it to 0 and keep traversing
as soon as it is not 9, we add+1 to value and break out of loop

Also we keep track whether we need to insert 1 at 0 index, ie if the we kept adding 1 till the 0th position and 0 was also 9.

18
Q

Rotate Matrix

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.
Input
123
456
789

Output
741
852
963

A

Its easy if we’re allwoed extra space because every column from bottom to top can become a row from left to right.
But if no extra space is allowed
We need to perform 4 replacements in rounds of iterations equal to the depth of matrix ie size/2 rounds
from outermost layer

A[i][j] = A[size-1-j][i];
A[size-1-j][i] = A[size-1-i][size-1-j];
A[size-1-i][size-1-j] = A[j][size-1-i];
A[j][size-1-i] = value;

eg
123
456
789

2 will go to 6, 6 to 8, 8 to 4 and 4 to 2