0% found this document useful (0 votes)
461 views39 pages

Uber Cracker Sheet

The document provides information about solving coding interview problems for Uber, including a link to a video that offers tips for optimally using a "Cracking the Uber coding interview" sheet. It then presents several coding questions and examples, ranging from finding the number of valid solutions to a math puzzle to determining the minimum cost of building a road network connecting tourist attractions. Constraints and test cases are provided for each problem.

Uploaded by

Abhishek Sood
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
461 views39 pages

Uber Cracker Sheet

The document provides information about solving coding interview problems for Uber, including a link to a video that offers tips for optimally using a "Cracking the Uber coding interview" sheet. It then presents several coding questions and examples, ranging from finding the number of valid solutions to a math puzzle to determining the minimum cost of building a road network connecting tourist attractions. Constraints and test cases are provided for each problem.

Uploaded by

Abhishek Sood
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Uber Cracker Sheet

- By Sunyul Hossen
🔥:
Note: [To Use this sheet optimally go and watch the "Cracking the Uber coding interview
The definitive prep guide" video on Debug Buzz Channel.
Link - https://youtu.be/CYKnE1FiVzU ]

Q) August 14th, 2022


Q) August 10th, 2022
A solution is a mathematical puzzle where the goal is to find the correspodence between
the letters and digits sucht that the given arithmetic equation consisting of letters holds
true.

Given a solution as an array of strings crypt, count the number of its valid solutions.

The solution is valid if each letter represents a different digit, and the leading digit of any
multi-digit number is not zero.

crypt has the following structure [word1, word2, word2], which stands for the word1 +
word2 = word3 solution

EXAMPLE

● For crypt = ["SEND", "MORE", "MONEY"] the output should be solution(crypt) = 1,


because there is only one solution to this solution:
O = 0, M = 1, Y = 2, E = 5, N = 6, D = 7, R = 8 and S = 9 (9567 + 1085 = 10652)

Q) August 5th, 2022


int solution(int n, int m, vector<vector> coins) {

Our Old Man is really old, and has no desire for money. His world is a NN X MM grid and
he lives in his cave at (1,1)(1,1). He want to meet his friend GodMan who lives in a
mountain at (N,M)(N,M).
There are X locations in this grid where we have a Coin.

But Old Man is on path to Nirvana and now doesn't want any money in his life and just
want to meet his friend.

Find the no. of Paths from (1,1)(1,1) to (N,M)(N,M) in which old man can reach his friend
while avoiding any coins in his path thus attaining nirvana. Since there can be too many
paths, so print it Modulo 10^{9} + 710

​9

​+7.

From any location (a,b)(a,b) he can only go to (a,b+1)(a,b+1) and (a+1,b)(a+1,b)

Additionally for any two locations with coins, lets say (a,b) and (p,q) we have either,

(aa \lt< pp and b\gt> qq) or (aa \gt> pp and bb \lt< qq)

Constraints

2 \le≤ N,MN,M \le≤ 100000

0 \le≤ XX \le≤ 5000

Sample Test Cases Explanation

Fot Test Case 1 -

4 Paths are

(1,1). -> (1,2) -> (2,2) -> (2,3) -> (3,3)

(1,1). -> (2,1) -> (2,2) -> (2,3) -> (3,3)

(1,1). -> (1,2) -> (2,2) -> (3,2) -> (3,3)

(1,1). -> (2,1) -> (2,2) -> (3,2) -> (3,3)

For Test Case 2 -

2 Paths are

(1,1) -> (1,2) -> (1,3) -> (2,3) -> (3,3)

(1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3)


[execution time limit] 1 seconds (cpp)

[input] integer n

n is the length of grid

[input] integer m

m is the width of grid

[input] array.array.integer coins

coins is a vector of vector int with each vector int containing exactly 2 integers indicating
the location of coin.

Additionally each coin lies within the grid. (see input in sample test cases for more
understanding)

[output] integer
Q) August 3rd, 2022

Explanation:- 101 -> 011 -> 000


input 2:- 11011

Output:- 3

Explanation:- 11011 -> 00111 -> 00000

Q) August 2nd, 2022


Teleporters allows players to randomize the teleporters each game. However, during
development they found that sometimes this can lead to boards where a player cannot get
to the end of the board. We want to figure out if this has happened.

You'll be given the following inputs:

● A collection of teleporter strings


● The number of sides on the die
● The square the player starts on
● The last square on the board

Write a function that returns whether or not it is possible to get to the last square from the
starting square in any number of turns.

Examples:

teleporters1 = ["10,8", "11,5", "12,7", "13,9"]

+------------------+

| +-----+ |

vv||

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

^^||

+-----|----------+ |

+--------------+

With a 4 sided die, starting at square 0 with a board ending at square 20 (as pictured
above)

No matter what you roll, it's not possible to get past the teleporters from 10-13.
finishable(teleporters1, 4, 0, 20) => False

If an additional teleporter was added from square 2 to square 15, this would be possible to
finish.

teleporters2 = ["10,8", "11,5", "12,7", "13,9", "2,15"]

finishable(teleporters2, 4, 0, 20) => True

But if we started on square 9,

Q) July 31st, 2022

Q) July 31st, 2022


Constraints

1≤ ∣a∣ ≤10^5

1≤ ∣b∣ ≤10^5

a and b consists of lowercase English letters.


Example:

Input

contest

son

Output

10

b=son is a subsequence of the string contestcon (the first 10 characters in a' =


contestcontestcontestcontest...), so i=10 satisfies the condition.

On the other hand, b is not a subsequence of the string contestco (the first 9 characters in
a'), so i=9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum
integer i satisfying the condition is 10.

Input

contest

sun

Output

-1

b= sun is not a substring of a' = contestcontestcontest.... Thus, there is no integer i


satisfying the condition.

Input

Input is given in the following format:

Q) July 31st, 2022


You are the mayor of a very old city. The city has n major tourist attractions. You are given
the locations (x, y, z) for each of these tourist attractions.
To boost the tourism in your city, you plan to create new roads that connect the tourist
attractions.
To create a bidirectional road between tourist attraction A (located at (x1, y1, z1)) and B
(located at (x2, y2, z2)), you need to spend min( |x1 - x2| , |y1 - y2| , |z1 - z2| ) dollars. Here
|x1 - x2| refers to the absolute value of x1 - x2, and min(x, y, z) refers to the minimum value
out of x, y and z.
You need to create a network of roads such that it is possible to travel between any pair of
tourist attractions using some sequence of roads. What is the minimum amount of dollars
you need to spend in order to accomplish this task?
Sample Input
n=3
locations =
[[1,5,7],
[2,9,4],
[1,3,9]]
Expected Output
1
Explanation
We can create 2 roads -
Road connecting attraction 1 (at (1, 5, 7)) and attraction 3 (at (1, 3, 9)). The cost of creating
this road is min ( | 1 - 1 | , | 5 - 3 | , | 7 - 9 | ) = min ( 0 , 2 , 2 ) = 0.
Road connecting attraction 1 (at (1, 5, 7)) and attraction 2 (at (2, 9, 4)). The cost of creating
this road is min ( | 1 - 2 | , | 5 - 9 | , | 7 - 4 | ) = min ( 1 , 4 , 3 ) = 1.
Creating these two roads enables us to travel between any pair of tourist attractions.
The total cost of creating these roads is 1 dollar.
[execution time limit] 1 seconds (cpp)
[input] integer n
The number of major tourist attractions in the city
2 <= n <= 100000
[input] array.array.integer locations
A matrix consisting of n rows. Each row has 3 integers - Xi, Yi, Zi - which describe the
location of the ith attraction.
All coordinates are integers, and
-100000 <= Xi, Yi, Zi <= 100000 for all i.
[output] integer64
The minimum amount in dollars that you need to spend in order to build the road network.
Q) July 31st, 2022
A farmer John has a piece of land divided into n sequential patches numbered from 0 to n
- 1. Initially, no patch has a crop in it. He wants to grow different kinds of crops in these
patches. He also has a sprinkler to water the crops, but it is faulty and sprinkles water at
different intensities each time it is used.

John sequentially carries out k events of one of the two types:

He grows a crop which has a water-withstanding capacity c in patch i (if that patch already
had a crop, it is removed to grow this new one)

He starts the sprinkler for the patches in the range from l to r - 1 which sprinkles water at
an intensity w. Due to this, all the crops in the patches l to r - 1 whose water-withstanding
capacity is not more than w (c ≤ w) get damaged and John needs to remove them.

Note: The water-withstanding capacity c of a crop having (c > w) does not decrease after a
sprinkling event.

You have to find out how many crops are damaged after each sprinkling event.

Input

n and k, the number of patches and the number of events respectively (1 ≤ n, k ≤ 200000).

A matrix events of size k to describe the events. Each event is a list and is described as
shown below:

[1, i, c]: A crop with water-withstanding capacity c is grown in patch i.

(0 ≤ i < n, 1 ≤ c ≤ 1e9)

[2, l, r, w]: Water with intensity w is sprinkled in the patches l to r - 1.

(0 ≤ l < r ≤ n, 0 ≤ w≤ 1e9)

Output

A list containing the number of crops damaged for each event of type 2 (sprinkling event).

Example

Input
n: 5

k: 9

events:

[[1,0,3],

[1,2,5],

[2,0,4,3],

[1,1,4],

[1,2,7],

[2,1,3,6],

[1,3,6],

[1,4,5],

[2,0,5,6]]

Output
[1, 1, 2]

Q) July 30th, 2022


There are two solid hoops coloures in black. A hoop is area between two concentric cirlce
with radius r and R (r<R). The two hoop lie on a completly white plane.

A colourful transition is a close continuos line through which there should be change of
colour. Given co-ordinate of two hoops find the number of circular colourful transitions.

Input:

Input contains two lines: description of each hoop.

Each line contains 4 space seperated integers:

x,y,r,R

where x,y is co-ordinate of center of the hoop. r and R are the radii of the smaller and
larger concentric circles of the hoop respectively.
Output:

A single integer: total possible number of circular colourful transition.

Constraints:

-100<=x,y<=100, 1<=r<R<=100

Sample Input

60 60 45 55

80 60 15 25

Sample Output

Q) July 30th, 2022


The "absolute sum" of an array is defined as the absolute value or the modulus of the
sum of its elements. For example, the array [4,-5,-6) has an absolute sum of while the
array [5,-4] has an absolute sum of 1. Let us define the "beauty" of an array as the
minimum of the absolute sums of all its subarray. A "subarray" is defined as a non-empty
sequence of consecutive elements of the array. An array is "beautiful" If It has a beauty
greater than zero. For example, the array [-4,5,7] is beautiful with a positive beauty of 1, as
its non-empty subarrays [-4], [5], [7), [-4,5]. [5,7], [-4,5,7] have absolute sums of 4, 5, 7, 1,
12 and 8 respectively On the other hand, the array [-1,1,3] is not beautiful as has a beauty
of O because of its subarray (-1,1].

Given an arr of length n, find its number of subarrays which are beautiful.

n<=10^5

Q) July 30th, 2022


https://codeforces.com/problemset/problem/159/D
Q) July 26th, 2022
Q) July 26th, 2022
https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/practic
e-problems/algorithm/permutation-again/
https://www.hackerrank.com/challenges/no-prefix-set/problem
https://codeforces.com/problemset/problem/799/C

Q) July 26th, 2022

Q) July 25th, 2022


Q) July 25th, 2022
We are given N cities and M bridges, each bridge connects two cities where it is possible
to travel from any one city to any other city using a sequence of bridges.

We want to divide these N cities into X disjoint groups G1, G2....Gx such that any one of
the following conditions meet for any bridge that connects two cities A and B:

if A belongs to Gi then B belongs to Gi+1 (1 <= i <= x-1)


if A belongs to Gi then B belongs to Gi-1 (2 <= i <= x)

Find the maximum value of X, or print -1 if such division is impossible

Constraints

2 <= N <= 250

Input Format

First line contains N, an integer

N line follows, one for each city, ith line contains N characters , where the jth character is
1 if there is a bridge between city i and j, else the character is 0

Sample Input 1

0111

1011

1101

1110

Sample Output 1

-1

Explanation

It is not possible to divide the cities into different groups by following the given
constraints

Sample Input 2

01

10

Sample Output 2
2

Explanation

City 1 can be in 1st group and city 2 can be in 2nd group, hence, max value of x is 2

Sample Input 3

011

100

100

Sample output 3

Explanation

City 2 can be in 1st group, city 1 can be in 2nd group and city 3 can be in 3nd group,
hence, max value of x is 3

[execution time limit] 3 seconds (java)

[input] integer n

[input] array.array.char mat

N line follows, one for each city, ith line contains N characters , where the jth character is
1 if there is a bridge between city i and j, else the character is 0

[output] integer

Value of X

Q) July 25th, 2022


There are N cities in a country, and all of them are connected by M roads. The country
council is planning a roadshow to visit all the N cities, and have asked you to organise it.

There is a fee E_i to host the show on each i_th road, and the total cost of roadshow is
defined as the bitwise OR of all road fees in the itinerary plan. The council has specifically
asked that there be no cycles in the final itinerary plan.
Find the minimum possible cost of roadshow in the country.

Example, we have a graph

Output : The minimum possible cost of roadshow will be by using the roads between
[[2,3], [1,3]]. And the bitwise OR is 2.

If we use lesser edges, the iternary wouldn't be connected.

If we used other combinations such as [[1,2],[2,3]] or [[1,2], [1,3]], the bitwise OR would be
3.

If we used all edges, the bitwise OR would be 3, and it will have cycles.

[execution time limit] 4 seconds (java)

[input] integer noOfCities

N = number of cities

3 <= N <= 2*10^5

[input] integer noOfRoads

M = number of roads

N-1 <= M <= 2*10^5


[input] array.array.integer roadFees

This is a Mx3 matrix. For each 0 <= i < E, roadFees[i] = [u_i, v_i ,E_i]

where u_i, v_i are the cities that the road connects and E_i its road fee

1 <= u_i, v_i <= N

1 <= E_i <= 10^9

[output] integer

Q) July 25th, 2022


Given 3 positive integers K,L,N where K≤L≤N

A integer set T of size L is called good if all integers in T are distinct and lie in range [1,N][1,N].

Let S be the set of all such possible sets T of given length LL.

Let A be the uniformly and randomly chosen set from S. J_AJ

​be the K^{th}K

​smallest integer in this set A. Find sum of J_A

​modulo 998244353998244353 over all such good sets A.

Since the problem is too easy for you, you will have to solve this for Q such query.

Input is given in form of 3 arrays Ks,Ls,NsKs,Ls,Ns each of size Q.

i^{th}i

​query consists of K = ks[i], L = ls[i], N = ns[i]K=ks[i],L=ls[i],N=ns[i]

Constraints:

1 <= Q <= 10^310

​3

1 <= K <= L <= N <= 10^610

​6

Sample Input

ks: [2, 1, 2, 3]

ls: [2, 1, 2, 3]

ns: [3, 1, 2, 3]

Sample Output

[8, 1, 2, 3]

Here, one has to solve for 4 different queries -

K=L=2,N=3K=L=2,N=3

K=L=N=1K=L=N=1

K=L=N=2K=L=N=2

K=L=N=3K=L=N=3

Lets look at K=L=2,N=3K=L=2,N=3 case -

TT has 3 possible sets (1,2)(1,2) , (1,3)(1,3) and (2,3)(2,3).

2nd smallest value in all of these sets resp. is 2,3,32,3,3, sum of these is 88.

[execution time limit] 3 seconds (java)

[input] array.integer ks

[input] array.integer ls

[input] array.integer ns

[output] array.integer

FUNCTION ->

1. int solution(int n, char[][] mat) {


}
2. int solution(int noOfCities, int noOfRoads, int[][] roadFees) {
}
3. int[] solution(int[] ks, int[] ls, int[] ns) {
}

Q) July 24th, 2022


There is a grid. O represents a Robot, X represents obstacle, E represents empty space
where you can move. Borders are also considered as an obstacle.

[O E E E E]
[E O X E E]
[X E X X E]
[E E O X E]
[X E X E E]

Query:

[2, 2, 4, 1]

Output: Robot at (1,1). List<int[]> is return type. Here, output will be [ {1,1} ].

Explanation: Robot at (1,1) has distance of 2 on left, 2 on top, 4 on bottom and 1 on right.

How is distance calculated? The robot at (1,1) has distance of 2 on left to border. E and
then the border, so distance of 2. Similarly, on the top E and then a border so distance of
2. On bottom, 3 E + border (out of bound) = 4. On right, obstacle X at distance of 1.

So, the query is [2,2,4,1] representing distance to obstacle on left, top, bottom, right. For
this query, robot at index (1,1) satisfies the query so return that robot. There might be
many robots in grid that satisfy the query or even none robot that satisfies this query

There can even be multiple robots satisfying this query. Return all the robots that satisfy
the query.

Consider this as a read heavy system. So, there will be lot of queries. Focus should be on
pre-computing efficiently.

Q) July 20th, 2022


A hotel has listed their opening and closing hours on their Facebook page for the week.
However hotel's social media manager, due to long working hours, is prone to making
mistakes while listing opening and closing hours on their social media page.

Help the hotel manager in correcting these mistakes. If there is an overlap in the multiple
intervals listed, merge those intervals. Output a list of intervals where there is no overlap.
Examples

Input1: [(Mon 9:00 -> Mon 17:00), (Tue 9:00 -> Tue 17:00)]
Output1: [(Mon 9:00 -> Mon 17:00), (Tue 9:00 -> Tue 17:00)]

Input 2: [(Fri 17:00 -> Sat 2:00), (Sat 1:00 -> Sat 15:00) ]
Output 2 : [(Fri 17:00 -> Sat 15:00) ]

Input 3: [(Mon 9:00 -> Mon 12:00), (Mon 12:00 -> Mon 17:00)]
Output 3: [(Mon 9:00 -> Mon 17:00)]

Q) July 16th, 2022


You are given a tree of N nodes rooted at node 1. The tree will be given as an array p of
size (N-1), where p[i] (0<=i<N-1) represents the parent of the (i+1)th node.

Each node also has a value associated with it, given as an array val of size N.

For each node V, you have to calculate the number of nodes in the subtree of V whose
value is co-prime with the value of V.

You need to return the sum of this value for all nodes in the tree as an answer.

Constraints

1 <= n <= 100000

1 <= val[i] <= 1000

array p represents a valid tree, rooted at node 1.

Sample Input:

n: 5

par: [1, 1, 3, 3]

val: [1,2,3,4,5]

Sample Output:

Sample Explanation:
par array is [1,1,3,3]. This means parent of node 2 and node 3 is 1, and parent of node 4
and node 5 is 3.
val array is [1,2,3,4,5]. This means values of nodes 1,2,3,4 and 5 are 1,2,3,4 and 5
respectively.

Q) July 6th, 2022


Given a 2D matrix of integers having only 0, 1 and 2.

0 repesents empty space

1 repesents robot

2 repesents blocker

There can be many robots in the matrix. The task was to return all the robots as per the
query below:

[2, 4, 3, 5] which means return all robots which have blockers at distance:

2 on the left from the current position of the robot

4 at the top from the current position of the robot

3 on the right from the current position of the robot

5 at the bottom from the current position of the robot

There can be several such queries.

Q) July 5th, 2022


https://leetcode.com/problems/task-scheduler/
Follow up - Print all tasks.

Q) June 23rd, 2022


Given n drivers on a road with position of ith driver defined as Xi and maximum speed of
vehicle Si. Find the minimum time taken for the cars to arrive at the same point?

Q) June 18th, 2022


Create hashmap which has functionality to add a value to all keys/values. After perfroming the
operations,return the sum of all gets on the hashMap.
ex: queries: ["insert", " addToValue", "get","insert","addToKey","addToValue","get"], corresponding
values for queries

parameters[][] : [[1,2],[2],[1],[2,3],[1],[-1],[3]]. Result: 6

Q) June 12th, 2022


Minimum number of additions to make array sorted (worded as adding blocks to towers)

EX:

arr = [1, 4, 3, 2]
result = 4 (Add 4 to the first item)

arr = [2, 3, 2, 3]
result = 4 (Add 2 to the last 2 items)

arr = [5, 7, 9, 4, 11]


result = 9 (add 2 to 5, add 1 to 7, 6 to 4)

Q) June 9th, 2022


Given a list of ranges of integers R, generate a set S such that

1. Each range of R has atleast 2 numbers in S


2. Size of S is minimum possible

Q) June 7th, 2022


A string A is called 'special' if it can be written like A = B + B. Empty string is also special.

Given a string S, you can perform :

i. Insert a new character anywhere inn the string.

ii. Remove a character.

iii. Replace character.

For a string, find the smallest possible number of steps to make given string S, a special string.

"xxxx","xyxy" and "abaaba" are examples of special strings.

"xxyy" and "xyx" are not special strings.


My Idea was to iterate at every position, and divide the string into two parts then find the
minimum number of steps to make the two strings equal(Like Edit String Problem). It Got TLE in
some test cases as the time complexity was O(n^3).

Example 1 :

Input : S1 = "aaxa"

Output : 1

Example 2 :

Input S1 = "cathatratmat"

Output : 2

Example 3 :

Input S1 : "aabcdeccdecc"

Output : 4

Constraint :

1 <= S.length <= 5000

Q) May 22nd, 2022


You are given an array of non-negative integers numbers. You are allowed to choose any
number from this array and swap any two digits in it. If after the swap operation, the
number contains leading zeros, they can be omitted and not considered (eg: 010 will be
considered just 10).

You task is to check whether it is possible to apply the swap operation at most once, so
that the elements of the resulting array are strictly increasing.

eg. [1,5,900,10] return true

Q) May 12th, 2022


You have a Log File in format

TimeStamp Name City

t1 John Seattle

t2 Doe Singapore
t3 John Delhi

t4 Doe Beijing

t2 John Beijing

t1 Doe Delhi

t4 John Singapore

t3 Doe Delhi

These are log of user and there location in a particular timestamp ( Long Format ) Order is non
sorted.

Create Sequential combination of cities for 3 consecutive timestamps (t1, t2, t3). (t2,t3,t4) etc
with count of users appearing in those cities accordingly.

e.g for t1, t2, t3

John is in -> Seattle Beijing Delhi

Doe is in -> Beijing Singapore Delhi

for t2, t3, t4

John is in Beijing Delhi Singapore

Doe is in Singapre Delhi Beijing

So the out put would be

( Seattle , Beijing , Delhi ) - 1

( Beijing Singapore Delhi ) - 1

(Beijing Delhi Singapore) - 1

(Singapre Delhi Beijing) - 1

and so on.

No limit in number of users or cities or timestamp. In Memory solution can be discussed, how
would you scale it from millions of logs.

Q) May 8th, 2022


You are given a binary string (containing character 0 and 1 only) s of length n. You task is to
convert all the 1s in this string to 0. To do this you can do the following :

First choose an integer K and then perform the following operation any number of times :

● Choose any substring of this string such that length of substring is greater than or equal
to K and change all 0s to 1 and all 1s to 0 in that substring i.e. for a substring [L,R]
(R-L+1>=K) in s, for each i such that L<=i<=R, if si is 0 make it 1 and if it is 1 make it 0.
Find the maximum integer K less than or equal to n that we can choose such that it is
possible to convert the string to all 0s using above method.
Constraints
1<=n<=100000
Examples
Input : 101
Output : 2
Explanation : If we choose K = 2, we can convert the string to all 0s by following way
● choose substring [0,1] = "10", then s becomes 011
● now choose substring [1,2] = "11", then s becomes 000
It is the maximum K as we can not convert the sting to all 0s by choosing K = 3.
Input : 10000
Output : 4
Explanation : We can choose K = 4 and convert the following way
● Choose substring [0,4] = "10000", the s becomes 01111
● Choose substring [1,4] = "1111", then s becomes 00000
Input/Output
● [execution time limit] 4 seconds (py3)
● [input] string s
given binary string
● [output] integer
Output the maximum K such that it is possible to convert s to all 0s by the operation.

Q) May 7th, 2022


Given three strings p, q, r. Count the possible number of ways to create string r using string p
and string q such that, the order of the selected characters in all the strings is preserved and at
least one character from both the strings (p and q) is selected.

Note
Strings will have max length 100

They will consist of lowercase english alphabets.

Return the answer modulo 10^9 + 7.

Sample test case

p: ab

q: ba

r: aba

output: 2

Two ways to form aba

from p, a, from q, ba

from p, ab, from q, a

[execution time limit] 1 seconds (cpp)

[input] string p

[input] string q

[input] string r

[output] integer

[C++] Syntax Tips

// Prints help message to the console

// Returns a string

string helloWorld(string name) {

cout << "This prints to the console when you Run Tests" << endl;

return "Hello, " + name;

}
Q) May 7th, 2022
You and your best friend leave messages for one another in your favorite places around town.
But you don't want any strangers to read them, so you hide them within strings. To decode a
message in a string you need to find a string subsequence of length 5 which is a palindrome -
this subsequence is the code itself.

Given a string message, return the number of such subsequences within it.

Example

For message = "abcdba", the output should be

solution(message) = 2.

You can obtain such palindromes: "abcba" and "abdba".

For message = "aabccba", the output should be

solution(message) = 4.

You can obtain "abcba" 4 times with different a and c from the given string.

Input/Output

[execution time limit] 0.5 seconds (cpp)

[input] string message

The encrypted message.

Guaranteed constraints:

1 ≤ message.length ≤ 700.

[output] integer

The number of subsequence palindromes with exactly 5 letters in the given string. It's
guaranteed that for the given test cases the answer always fits signed 32-bit integer type.

[C++] Syntax Tips

// Prints help message to the console

// Returns a string
string helloWorld(string name) {

cout << "This prints to the console when you Run Tests" << endl;

return "Hello, " + name;

Q) May 7th, 2022


You are given a tree of N nodes rooted at node 1. The tree will be given as an array p of
size (N-1), where p[i] (0<=i<N-1) represents the parent of the (i+1)th node.

Each node also has a value associated with it, given as an array val of size N.

For each node V, you have to calculate the number of nodes in the subtree of V whose
value is co-prime with the value of V.

You need to return the sum of this value for all nodes in the tree as an answer.

Constraints

1 <= n <= 100000

1 <= val[i] <= 1000

array p represents a valid tree, rooted at node 1.

Sample Input:

n: 5

par: [1, 1, 3, 3]

val: [1,2,3,4,5]

Sample Output:

Sample Explanation:

par array is [1,1,3,3]. This means parent of node 2 and node 3 is 1, and parent of node 4
and node 5 is 3.
val array is [1,2,3,4,5]. This means values of nodes 1,2,3,4 and 5 are 1,2,3,4 and 5
respectively.

The tree looks like this:

Sample Tree

For node 1, the nodes in its subtree whose values are co-prime with value of 1, i.e. 1 are:
2,3,4 and 5. Count: 4

For nodes 2,4 and 5 there are no such nodes as they have no subtree.

For node 3, the nodes in its subtree whose values are co-prime with value of 3 i.e. 3 are: 4
and 5. Count: 2.

So final answer = 4 + 2 = 6.

Input Generation

You are not directly given the arrays p and val. Instead you are given four integers N,
seed, l, r and s for randomly generating the arrays p and val. Use the following stub to
begin with:

int p[100001], val[100001]; // global arrays which will be randomly generated by below
function

void generateTree(int N, int seed, int L, int R, int S) {

srand(seed);

for(int i=1;i<=N-1;i++) {
p[i] = max(1, i-S+1) + (rand() % (i+2 - max(1, i-S+1))); // random node
in [i-S+1, i+1]
}

for(int i=1;i<=N;i++) {
val[i] = L + rand() % (R-L+1); // random integer between L and R
}

long long solution(int n, int seed, int l, int r, int s) {

generateTree(n, seed, l, r, s); // Call the random generator to generate p and val arrays first
// Write your code from here

[execution time limit] 3 seconds (cpp)

[input] integer n

The number of nodes in the tree. 1 <= n <= 100000

[input] integer seed

parameter for random generation

[input] integer l

parameter for random generation

[input] integer r

parameter for random generation

[input] integer s

parameter for random generation

[output] integer64

The sum of the number of co-prime values in the subtree, for each node.

Q) April 30th, 2022


Given two time series data lists,

First List

[(1, 3), (3, 1), (5,3), (6, 4), (10, 1)]

Explanation:

What this means is that at timestamp 1 the value is 3, and then at timestamp 3 the value is 1 and
so on.
Note: Missing/Undefined value on any timestamp is extrapolated backwards from the next
timestamp. For example, value at timestamp 2 based on the example above would be 1.

Second List

[(2, 3), (6, 3), (9, 2)]

Write a function to aggregate these two time series data into one

Answer

[(1, 6), (2, 4), (3, 4), (5,6), (6, 7), (9, 3), (10,1)]

Q) April 28th, 2022


Given a grid that shows a connected object at it's current position where 'F' indicates the object
and '#' indicates an obstacle, return the grid with the final position of the object once it falls down
due to gravity.

Example:

Input:

[[ '.', 'F', '.'],

['F', 'F', 'F'],

['.', 'F', '.' ],

['.', 'F', '.' ],

['#', '.', '.'],

['.', '.', '.']]

Output:

[[ '.', '.', '.'],

['.', '.', '.'],

['.', 'F', '.'],

['F', 'F', 'F' ],

['#', 'F', '.'],


['.', 'F', '.']]

It is guaranteed that there is a path through the object connected by it's sides and not through it's
corners.

Q) April 28th, 2022


There is a function called rev(int) that returns the number with the digits reversed i.e. rev(3200) =
23, rev(5) = 5, rev(72) = 27. Given an array arr, return the number of pairs of indices i, j where i
<= j where arr[i] + rev(arr[j]) = arr[j] + rev(arr[i)).

Q) April 27th, 2022


https://leetcode.com/problems/reconstruct-itinerary/

Follow up - What if multiple routes are available and output the longest route possible.

[["JFK","SFO"],["ATL","CDG"],["SFO","ATL"],["CDG","MAA"],["MAA","ORD"],["ORD","DFW"],["CD
G","DXB"]]

Valid routes -

JFK - SFO - ATL - CDG - MAA - ORD - DFW

JFK - SFO - ATL - CDG - DXB

Output should be JFK - SFO - ATL - CDG - MAA - ORD - DFW

Q) April 27th, 2022


You a captain of a ship. Initially you are standing in a point (𝑥1,𝑦1)
(obviously, all positions in the sea can be described by cartesian plane)
and you want to travel to a point (𝑥2,𝑦2).

You know the weather forecast — the string 𝑠 of length 𝑛, consisting only
of letters U, D, L and R. The letter corresponds to a direction of wind.
Moreover, the forecast is periodic, e.g. the first day wind blows to the
side 𝑠1, the second day — 𝑠2, the 𝑛-th day — 𝑠𝑛 and (𝑛+1)-th day — 𝑠1 again
and so on.

Ship coordinates change the following way:


if wind blows the direction U, then the ship moves from (𝑥,𝑦) to (𝑥,𝑦+1);

if wind blows the direction D, then the ship moves from (𝑥,𝑦) to (𝑥,𝑦−1);

if wind blows the direction L, then the ship moves from (𝑥,𝑦) to (𝑥−1,𝑦);

if wind blows the direction R, then the ship moves from (𝑥,𝑦) to (𝑥+1,𝑦).

The ship can also either go one of the four directions or stay in place
each day. If it goes then it's exactly 1 unit of distance. Transpositions
of the ship and the wind add up. If the ship stays in place, then only the
direction of wind counts. For example, if wind blows the direction U and
the ship moves the direction L, then from point (𝑥,𝑦) it will move to the
point (𝑥−1,𝑦+1), and if it goes the direction U, then it will move to the
point (𝑥,𝑦+2).

You task is to determine the minimal number of days required for the ship
to reach the point (𝑥2,𝑦2).

Q) April 13th, 2022


There are N people who want to visit the haunted house. The person will only go if at least
L other people will go with him. Additionally, that person doesn't want to go with more
than R other people, since it would ruin the experience for them.

What is the maximum number of people that can visit the haunted house at one time so
that no constraint is violated?

Sample Input:

// The number of people

// L R

1 2

1 4

0 3

0 1

3 4

0 2

Sample Output
3

Q) April 13th, 2022


https://leetcode.com/problems/my-calendar-i/

https://leetcode.com/problems/bus-routes/

Q) March 17th, 2022


Find the lowest, highest, median price of a stock, you will be altered when the price of a
stock is updated.. so the stock will be comming like a stream...Finding a meadian i see lot
of solutons online, but i don't see any solution for finding the lowest and highest value
until now..

Ex Input:

Stock:

19878800 - > $2,541.07

19878801 - > $2,000.01

19878802 - > $3,600.08

19878803 - > $500.04

19878804 - > $1000

write the methods for lowest(), highest() stock until now.. the stream will continue..
whenever we call this function it should return the lowest value of the stock till now, and if
we call the highest value function, it should return the highest value of stock till now.

Q) March 5th, 2022


X and Y were in an election battle in their city. This city consists of N towns, and each
town has M1 number of people who will vote for Y and M2 number of people who will not
take part in the election. X after seeing the lack of his supporters, decided to campaign.

If X does a campaign in town T, both M1 and M2 number of people in this town become his
supporters.

Your task is to calculate the least number of towns in which X has to campaign to win the
election.
Note: It is always possible for X to win the election.

Constraints:

1 < N<= 200000

1< M1,M2 <= 1000000000

Test Case

22

22

Answer: 1

Explanation: X can campaign in either city and gain 4 votes, Y can thus only get a
maximum of 2 votes

Test Case #2:

22

13

51

22

Answer: 1

Explanation: X needs to campaign in city 3 to gain 5 + 1 = 6 votes. Y can only get a


maximum of 2 + 2 + 1 = 5 votes.

You might also like