Sprinklr

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Contents

1 Set 1 (On-Campus at IIT Kanpur) 2


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Set 2 (On-Campus) 3
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3 Set 3 (On Campus for FTE) 4


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

4 Set 4 (For SDET) 6


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

5 Set 5 (On campus – FTE for Product Engineer) 8


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

6 Sprinklr Internship Interview Experience 11


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

7 Sprinklr Interview Experience 14


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

8 Sprinklr On Campus Internship 15


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

9 Mobile Numeric Keypad Problem 18


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

1
Chapter 1

Set 1 (On-Campus at IIT


Kanpur)

Sprinklr Interview Experience | Set 1 (On-Campus at IIT Kanpur) - GeeksforGeeks


An online test(2 hours) which has two sections.
They asked 16 questions in the first section (20 minutes) which were objective. It consisted
of questions from Operating systems, Networks, Java based MCQ(theory+output), C/C++
based questions(theory + output), etc.
Second section had 4 coding questions (1 hr 40 minutes). One of those was an avg question.
Rest three were good thinking questions.

Source

https://www.geeksforgeeks.org/sprinklr-recruitment-test/

2
Chapter 2

Set 2 (On-Campus)

Sprinklr Interview Experience | Set 2 (On-Campus) - GeeksforGeeks


Sprinklr On-Campus Interview Experience :
Round 1 : (Hackerrank test) 1hr
40 technical and aptitude mcqs , mostly technical from almost all topics(C,java,DBMS,OS,Networks,DS-
Algo etc.)
questions were of medium standard.
Round 2: (Coding test) 1.5hr
Consisted of 3 questions. 2 were very easy and one was medium.
Q. Don’t remember q1 but the logic was very simple (it was just some kind of adding and
checking which is greater)
Q. Given array , find number of distinct pair with sum K.
Q. Given an array of 0s,1s , have to flip(0 becomes 1 and 1 becomes 0) a particular portion
of array (a sub array) such that over all number of 1s is maximum.
Round 3 : (F2F) 30-45 min.
There was nothing in this round .Just the discussion on 3 questions in coding round and
the below one.
Q. Code for top k restaurants near by you.
Round 4 : (F2F) 30-45 min.
Q. http://geeksquiz.com/puzzle-19-poison-and-rat/
Q. Given huge data (>10TB) .Find all the documents which contain the string “Sachin
plays cricket”.
Q. https://www.geeksforgeeks.org/mobile-numeric-keypad-problem/
Q. Garbage collection in java ,What is Finalize method?

Source

https://www.geeksforgeeks.org/sprinklr-interview-experience-set-2-on-campus/

3
Chapter 3

Set 3 (On Campus for FTE)

Sprinklr Interview Experience | Set 3 (On Campus for FTE) - GeeksforGeeks


Online Test: 720 points
The test was conducted on hackerearth platform, consisted of 2 sections.
Section 1: 120 points.
30 MCQs. Marking scheme: +4 -1
Some questions were subject related OS,CNS,DBMS. Some were from C,Java input output,
basic concepts.
Others technical questions related to Trees, Graphs, sorting, etc.
Section 2: 600 points.
4 coding questions. 2 of 100 points, 2 of 200 points.
100 points: The question was similar to this one. https://www.geeksforgeeks.org/
maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
100 points: It was related to Math, modulus arithmetic. There were complicated expressions
given to be evaluated, but if solved, they got reduced to a single expression. That was the
catch in the problem. Otherwise, the solution would result in TLE.
200 points: Related to binary search.
200 points: Data was given. It had to be manipulated following given steps, and the output
to be printed. Brute force did not work, gave result TLE.
Total 40 students were shortlisted for interviews after the online test.
Interview Round-1: Technical: 45-50 minutes
There were two interviewers.
The first interviewer looked at my resume, and asked questions related to my industrial
internship.
He asked me about the course projects – Software Engineering project and Database project.
Also asked questions about an App I had developed and written in the resume.
The second interviewer asked me about my approach to the coding questions in the online
round, even about the ones I was not able to attempt.
Then, questions related to OS. Mainly scheduling and applications.
Then, 1 probability question. A few questions related to trees and sorting.

4
Chapter 3. Set 3 (On Campus for FTE)

Interview Round-2: Technical: 45-50 minutes


There were two interviewers.
First I was asked about my industrial internship. Then, a couple of questions related to
Java.
The first interviewer asked me the following question:
Given m,n dimensions of a 2D matrix; (i,j) initial co-ordinates; (x,y) final co-ordinates.
What is the probability of being at (x,y) after at most k steps if we start from (i,j) initially?
First, I thought about it and explained my approach. I was then asked to write a pseudo code
on paper for the same. I explained the code and answered questions related to complexity
of code, improvements.
The second interviewer asked me the following question:
If a user comes to you with a request to design a mobile for him, what will be your approach?
I was asked to explain whatever points I was saying, had to answer all the counter questions.
Interview Round-3: HR round: 25-30 minutes
This was a typical HR interview.
First I was asked to introduce myself. Questions related to my hobbies, my areas of interest.
Why Sprinklr?
Are you planning for further studies?
She told me things about the work environment in the company and the compensation
policy.
At the end, total 13 students were selected.

Source

https://www.geeksforgeeks.org/sprinklr-interview-experience-set-3-campus-fte/

5
Chapter 4

Set 4 (For SDET)

Sprinklr Interview Experience | Set 4 (For SDET) - GeeksforGeeks


Round 1: First round was on HackerEarth consisting of MCQ’s (technical and aptitude
both) with 2 coding questions.

1. https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/
2. I don’t remember.

12 students were shortlisted and were called to their Gurgaon office.


Round 2:

1. OOP related questions (inheritance, polymorphism).


2. Data Structure basic questions like linked list, doubly linked list, BFS, DFS, Trees.
3. Find the height of node using 2 queues afterwards 1 queue.
4. Spiral matrix
5. Sort the array consisting 0’s and 1’s (minimum complexity).
6. Find the subset of array consisting k sum.
7. Hashing (project related)

Round 3:
More Array related questions from geeksforgeeks.

1. Database queries (second max), view in database, etc.


2. Given a scenario of a customer placing order on ecommerce site, invoice is generated.
How to validate the invoice? Test cases for invoice validation.
3. Project related questions on networking.
4. Basic questions of ER diagram and asked to design a simple ER diagram of a company.

Round 4:
So far experience of previous rounds was asked. It was a puzzle round.

6
Chapter 4. Set 4 (For SDET)

1. Angle between minute hand and hour hand.


2. https://www.geeksforgeeks.org/puzzle-9-find-the-fastest-3-horses/

Please Improve this article if you find anything incorrect by clicking on the ”Improve Article”
button below.

Source

https://www.geeksforgeeks.org/sprinklr-interview-experience-set-4-sdet/

7
Chapter 5

Set 5 (On campus – FTE for


Product Engineer)

Sprinklr Interview Experience | Set 5 (On campus - FTE for Product Engineer) - Geeks-
forGeeks
Online Coding Test (2 hours):
There were 15 MCQs based on Data Structures and Algorithms, JavaScript, c++, Java,
Time Complexity Analysis. 3 coding questions were given.
1) You are given a string consisting lowercase letters. You have to find number of substrings
in which all characters are different.
Constraint: 1 <= length of string N <= 100000
Expected Complexity: O(N)
2) You are given an array. You have to find a subset from this array such that average of
elements of this subset is less than or equal to k.
Constrains: 1 <= length of array N <= 100000, 1 <= k <= 10^9.
Expected Complexity: O(N logN)
3) You are given a graph of n nodes with m bidirectional edges. Each edge has some value
associated with it. Vertex 1 is source vertex. You have K wildcards. In the path from
vertex 1 to vertex i (2 <= i <= n), you can use atmost K wildcards while traversing. When
you use a wildcard on an edge, you can pass that edge in summing the cost of path (i.e.
value of that edge will be 0 if you use a wildcard on an edge). Note: You can use atmost K
wildcard from vertex 1 to vertex 2. Now you can again use atmost K wildcards from vertex
1 to vertex 3 and so on to vertex n. i.e. You can use atmost K wildcards in each path from
source to destination. You have to find minimum distances from node 1 to all other nodes
in graph.
Constraints: 1 <= n,m <= 500000, 1 <= K <= 15
Expected Approach: DP with shortest path algorithms on graph.
Round 1 (Technical):
1) Draw relational schema of your DBMS course project.
2) Write some queries related to your project.
3) What is hashing? What are different schemes for hashing?

8
Chapter 5. Set 5 (On campus – FTE for Product Engineer)

4) What is load factor and rehashing?


5) Pseudo code of quick sort.
Round 2 (Technical):
1) System Design – TinyURL system – Two functions – get() and set(). Get() method takes
shorter URL and redirect to main longer url. Set() method takes longer url and gives shorter
url. (All about how you will implemented in database – how will you store your data such
that retrieval will be optimal.)
2) How will you handle critical sections? What happens when your system crashes?
3) System Design – Mall system (Define 4-5 functionalities. What tables you can make for
database to satisfy all these functionalities? How will you store data on the disk efficiently
– concept of AVL tree or B+-tree).
4) Write a code about detect cycle in undirected graph.
Round 3 (Extra Technical for some students):
1) Puzzle: Two trains come to each other with 50 kmph and 70 kmph respectively. There is
a bee on a train 1. It travels to train 2 with speed 80kmph. Immediately after reaching at
train 2, it goes back again at train 1 with same speed. It does this until trains collide. You
have to determine the distance bee covers until trains collide.
2) Puzzle: There are 25 horses. You have to make minimum number of races to determine
first 3 winner horses.
3) System Design – Parking lot system. There are many floors. On each floors, there are
many rows of parking slots. There are 3 types of parking slots – Tiny, Medium, Big. You
can park bike, car or bus. Bike can be parked at any type of slot. Car can be parked either
at Medium slot or Big slot. Bus can be parked by taking 5 consecutive parking slots of
big type. Design system in terms of OOP concepts – make classes, class diagram, methods,
variables.
4) You are given pipe of L length (Assume as X – axis and opening of pipe is at coordinate L).
There are many droplets on various x coordinates in pipe. Each droplet has some velocity
in right direction. When two droplets collide with each other, they merge and accepts the
smaller velocity. At L, how many droplets will be out?
5) You are given a linked list. You have to find length of loop.
Round 4 (HR round):
1) What are your hobbies?
2) What one thing that you proud of yourself?
3) How was your experience about earlier interview rounds?
4) What was most challenging part of your earlier interview rounds?
5) When in your life, you felt that you are a failure?
6) What is your dream company other than sprinklr?
7) What is your weakness?
At the end, total 8 students were selected.

Please Improve this article if you find anything incorrect by clicking on the ”Improve Article”
button below.
Improved By : TapanModi

9
Chapter 5. Set 5 (On campus – FTE for Product Engineer)

Source

https://www.geeksforgeeks.org/sprinklr-interview-experience-set-5-on-campus-fte-for-product-engineer/

10
Chapter 6

Sprinklr Internship Interview


Experience

Sprinklr Internship Interview Experience - GeeksforGeeks


Round 1 (Coding) : It was conducted on HackerRank .
Question – 1 : Given a tree with n nodes rooted at given root node r and having values
associated with all the nodes. You have to answer two types of queries :-

1. sum i – In this query you have to print the sum of the sub-tree of the node i including
the node i .
2. update i, k :- In this query you have to increase the value of the i-th node by value k

Question – 2 : Given a string (1-based indexed) having only lowercase english alphabets of
length n . You are given q queries and a range [l, r] with each query . You have to print
count of all the sub-strings which are ending and starting with the same character for each
query.
Example – abacc
3 queries –
12
24
15
Output :-
2
3
7

11
Chapter 6. Sprinklr Internship Interview Experience

Question – 3 : You are given an array a with positive integers . You have to print the size
of the smallest subset such that the bitwise or of the array is maximum.
Example : 5 1 3 4 2
output :- 2
Explanation :- maximum or of array is 7 . subset chosen – [2, 5] or [3, 4].
Round – 2 :- This was an offline technical round which lasted for about half an hour .
Interviewer started with my introduction like tell me about yourself and all that stuff. In
that time he was going through my resume and pointed out my interests in competitive
programming and started with his questions.
Questions in Round 2 :-

1. First question was you are given n balls on the table and all the balls are rolling
towards the one end of the table with velocities V1, V2, V3, V4……Vn and there is a
bucket placed at that end. Distance of the ball with velocity V1 from the end of the
table where bucket is placed is D1 similarly distance of ball with velocity V2 is D2
and so on.. Now it is given that when two balls collide both the balls merge into each
other and move with velocity of the ball nearer to the bucket . So at last you have to
tell the number of the balls which will fall into the bucket..
2. Puzzle :- You have 10 bags full of balls. In each bag are infinite balls. But one bag is
full of forgeries, and you can’t remember which one. But you do know that a genuine
ball weigh 10 gram, but forgeries weigh 5 grams. You have to identify that bag in
minimum readings. You are provided with a digital weighing machine.
3. Then he slightly changed the above puzzle and asked me like if instead of one bag if
two bags have forgeries then in how many minimum number of readings you will find
out the both bags.
4. What is a red-black tree.. Code
5. What is an AVL tree..Code
6. How you will detect a cycle in an directed or undirected graph.
7. You are given a graph with some of its edges are directed and some are un-directed.
You have to return true/false depending upon if you can convert all the undirected
edges in directed ones such that there is no cycle in graph return true else return false..
8. Then he asked me some basic OOPs concepts like :

• what is Encapsulation ?
• What is run-time and compile-time polymorphism ?
• what is data-hiding and how it is helpful. ?
• difference between c++ and java.

Then, Atlast he asked me if i have any questions to ask him ..


Round 3 :- This was an HR round .. She asked me the standard questions like tell me about
yourself, What do you know about our company, who are our clients, are you comfortable
with the location and the stipend ..
Some Important Tips :-

12
Chapter 6. Sprinklr Internship Interview Experience

1. Be very strong in competitive programming and data structures and algorithms. Data
structures is the heart of all the companies every company will definitely ask that.
2. Be active on codechef, codeforces or any other competitive coding website and get
familiar with the online ide such that hackerrank, hackerearth most of the company’s
online round will be on hackerrank only.
3. Try to score very good in online coding round because they see your ranks and it
might be very helpful if you scored good in your online round it’ll be definitely a plus
point for you.
4. Try to be confident in front of interviewer . Try to make a friendly environment with
him/her and don’t hesitate to ask hints if you got stuck in any question it will show
your compatible nature.
5. Do some homework about the company like what the company does every HR will ask
that question.

ALL THE BEST..

Please Improve this article if you find anything incorrect by clicking on the ”Improve Article”
button below.

Source

https://www.geeksforgeeks.org/sprinklr-internship-interview-experience/

13
Chapter 7

Sprinklr Interview Experience

Sprinklr Interview Experience - GeeksforGeeks


Round 1: So this was the first tech round . When i entered the room he asked me to tell me
about myself so i started to tell him about me like my higher education, my extra curricular
activities in school and then i told him about my competitive programming interests so he
asked my codeforces and codechef profiles ..Then he began with the questions .

1. First question was you are given n balls on the table and all the balls are rolling
towards the one end of the table with velocities V1, V2, V3, V4……Vn and there is a
bucket placed at that end. Distance of the ball with velocity V1 from the end of the
table where bucket is placed is D1 similarly distance of ball with velocity V2 is D2
and so on.. Now it is given that when two balls collide both the balls merge into each
other and move with velocity of the ball nearer to the bucket . So at last you have
two tell the number of the balls which will fall into the bucket..
2. Then he asked me are you familiar with red-black tree and to implement it
3. Third question was to implement AVL tree.
4. The last question was a graph question . You are given a graph with some edges
directed and some undirected edges. you have to return true if you can make the
undirected edges as directed such that there is no formation of cycle in whole graph
otherwise return false.

Round 2: This was an HR round . She asked me about myself and about my interests
and my hobbies.. Then she asked me about the company like in which field they are active
who are their clients all that stuff ..

Please Improve this article if you find anything incorrect by clicking on the ”Improve Article”
button below.

Source

https://www.geeksforgeeks.org/sprinklr-interview-experience/

14
Chapter 8

Sprinklr On Campus Internship

Sprinklr On Campus Internship - GeeksforGeeks


Sprinklr visited our campus as part of Internship Drive. Around 170 students of CSE, ECE
and EEE participated in the First Round.Details goes like this.
Round 1:(Technical Aptitude + Coding) – 450 Marks

The first round comprised of 20 Technical Aptitude and 3 Coding Questions and was held on
HackerEarth platform.It was of 2 hrs duration and each of the aptitude question weighted
5 marks without any negative marking.Coding questions were as follows:
Question 1: You are given a general tree with n nodes, each node is associated with a
certain value, rooted at node r. You have to answer q queries which can be either of the
following two types.
1. sum i :- given the value of node i, print the sum of the subtree rooted at i including its
value.
2. update i, k :- update the value of node i to k.
(200 Marks)
Question 2: You are given an array consisting of non-negative integers.You have to find
the size of the smallest subset such that the Bitwise OR of that set is maximum possible.
Sample Testcase : 5 1 3 4 2
Sample Output : 2
Clarification : Max possible OR is 7, which can be achieved by [5, 2] or [3, 4]
(50 Marks)
Question 3: You are given a string of length n (1-based indexing) having only the lowercase
english alphabets.You have to answer q queries each consisting of two integers l, r. For each
query you have to return the count of all sub-strings in range [l, r] (both l and r inclusive)
such that its starting and ending characters are same.

15
Chapter 8. Sprinklr On Campus Internship

Sample Testcase : aabacc


Queries
25
12
16
Sample Output :
5
3
10
(100 Marks)
Finally 21 Students were selected for the next round.
Round 2:(Technical Face to Face Interview)

This round was a formal interview conducted by the company officials.It started with a
brief introduction of mine including a mention of all my favorite subjects.Meanwhile the
interviewer went through my Resume and now he started with the questions.
Firstly he asked me about the project mentioned in my Resume to tell about the Frameworks
used in it and the reason for choosing it as a project.
Then he moved on to Tech Questions which are listed below.

1. You are given an array and you have to answer q queries, each query is given with two
integers l and r. In each query you have to tell the sum of all array elements between
indices l and r.Tell the best space and time efficient method.
2. Now suppose there’s an update query which changes certain elements of the array
alongwith the Range Sum Query.Tell the Data Structure which supports this with
best space and time complexity.
3. Logical Implementation (not actual code) of Segment Tree for Range Queries (basically
related to above two questions only).
4. Which properties of DBMS makes it worthy enough to hold and operate Relational
Data.
5. Description of ACID properties.
6. You have to implement a Task Scheduler where tasks are coming in continuous
stream.Each task is associated with two kind of information, its name and its priority
value.Now the task scheduler works in such a way that every time the task which is
going to execute next must be highest in priority among all the tasks arrived till its
execution starts.
Tell the Data Structure to implement it and explain the logic.(Hint: Max Heap,
Topological Sorting).
7. You are given a string in JAVA which actually represents a floating point number.You
have to convert this number to a long integer without any data loss.Use of library
functions are allowed.

16
Chapter 8. Sprinklr On Campus Internship

Finally he asked me if I have any questions for him.


Round 3:(HR)
This round was last stage of the series.It started with the common question Tell me about
yourself and proceeded with the questions like Why Sprinklr, What is your under-
standing about the company, What are your Expectations from the company,
Is the location comfortable for you and few others.

Finally total 5 students were listed in the final selections and I was one among them.
It was a quite a good experience and Competitive Programming , Data Structure
Concepts and my Confidence helped me a lot to grab this opportunity.
Good Luck to ALL.

Please Improve this article if you find anything incorrect by clicking on the ”Improve Article”
button below.

Source

https://www.geeksforgeeks.org/sprinklr-on-campus-internship/

17
Chapter 9

Mobile Numeric Keypad


Problem

Mobile Numeric Keypad Problem - GeeksforGeeks


Given the mobile numeric keypad. You can only press buttons that are up, left, right or
down to the current button. You are not allowed to press bottom row corner buttons (i.e.
* and # ).

Given a number N, find out the number of possible numbers of given length.
Examples:
For N=1, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N=2, number of possible numbers would be 36
Possible numbers: 00,08 11,12,14 22,21,23,25 and so on.
If we start with 0, valid numbers will be 00, 08 (count: 2)
If we start with 1, valid numbers will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers will be 55,54,52,56,58 (count: 5)
………………………………

18
Chapter 9. Mobile Numeric Keypad Problem

………………………………
We need to print the count of possible numbers.
N = 1 is trivial case, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N > 1, we need to start from some button, then move to any of the four direction (up,
left, right or down) which takes to a valid button (should not go to *, #). Keep doing this
until N length number is obtained (depth first traversal).
Recursive Solution:
Mobile Keypad is a rectangular grid of 4X3 (4 rows and 3 columns)
Lets say Count(i, j, N) represents the count of N length numbers starting from position (i,
j)

If N = 1
Count(i, j, N) = 10
Else
Count(i, j, N) = Sum of all Count(r, c, N-1) where (r, c) is new
position after valid move of length 1 from current
position (i, j)

Following is C implementation of above recursive formula.

// A Naive Recursive C program to count number of possible numbers


// of given length
#include <stdio.h>
  
// left, up, right, down move from current location
int row[] = {0, 0, -1, 0, 1};
int col[] = {0, -1, 0, 1, 0};
  
// Returns count of numbers of length n starting from key position
// (i, j) in a numeric keyboard.
int getCountUtil(char keypad[][3], int i, int j, int n)
{
    if (keypad == NULL || n <= 0)
        return 0;
  
    // From a given key, only one number is possible of length 1
    if (n == 1)
        return 1;
  
    int k=0, move=0, ro=0, co=0, totalCount = 0;
  
    // move left, up, right, down from current location and if
    // new location is valid, then get number count of length
    // (n-1) from that new position and add in count obtained so far
    for (move=0; move<5; move++)

19
Chapter 9. Mobile Numeric Keypad Problem

    {
        ro = i + row[move];
        co = j + col[move];
        if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
           keypad[ro][co] != '*' && keypad[ro][co] != '#')
        {
            totalCount += getCountUtil(keypad, ro, co, n-1);
        }
    }
  
    return totalCount;
}
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    // Base cases
    if (keypad == NULL || n <= 0)
        return 0;
    if (n == 1)
        return 10;
  
    int i=0, j=0, totalCount = 0;
    for (i=0; i<4; i++)  // Loop on keypad row
    {
        for (j=0; j<3; j++)   // Loop on keypad column
        {
            // Process for 0 to 9 digits
            if (keypad[i][j] != '*' && keypad[i][j] != '#')
            {
                // Get count when number is starting from key
                // position (i, j) and add in count obtained so far
                totalCount += getCountUtil(keypad, i, j, n);
            }
        }
    }
    return totalCount;
}
  
// Driver program to test above function
int main(int argc, char *argv[])
{
   char keypad[4][3] = {{'1','2','3'},
                        {'4','5','6'},
                        {'7','8','9'},
                        {'*','0','#'}};
   printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));

20
Chapter 9. Mobile Numeric Keypad Problem

   printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));


   printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
   printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
   printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
  
   return 0;
}

Output:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

Dynamic Programming
There are many repeated traversal on smaller paths (traversal for smaller N) to find all
possible longer paths (traversal for bigger N). See following two diagrams for example. In
this traversal, for N = 4 from two starting positions (buttons ‘4’ and ‘8’), we can see there
are few repeated traversals for N = 2 (e.g. 4 -> 1, 6 -> 3, 8 -> 9, 8 -> 7 etc).

21
Chapter 9. Mobile Numeric Keypad Problem

Since the problem has both properties: Optimal Substructure and Overlapping Subproblems,
it can be efficiently solved using dynamic programming.
Following is C program for dynamic programming implementation.

// A Dynamic Programming based C program to count number of


// possible numbers of given length
#include <stdio.h>
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    if(keypad == NULL || n <= 0)
        return 0;
    if(n == 1)
        return 10;
  
    // left, up, right, down move from current location
    int row[] = {0, 0, -1, 0, 1};
    int col[] = {0, -1, 0, 1, 0};
  
    // taking n+1 for simplicity - count[i][j] will store
    // number count starting with digit i and length j
    int count[10][n+1];
    int i=0, j=0, k=0, move=0, ro=0, co=0, num = 0;
    int nextNum=0, totalCount = 0;
  
    // count numbers starting with digit i and of lengths 0 and 1
    for (i=0; i<=9; i++)
    {

22
Chapter 9. Mobile Numeric Keypad Problem

        count[i][0] = 0;
        count[i][1] = 1;
    }
  
    // Bottom up - Get number count of length 2, 3, 4, ... , n
    for (k=2; k<=n; k++)
    {
        for (i=0; i<4; i++)  // Loop on keypad row
        {
            for (j=0; j<3; j++)   // Loop on keypad column
            {
                // Process for 0 to 9 digits
                if (keypad[i][j] != '*' && keypad[i][j] != '#')
                {
                    // Here we are counting the numbers starting with
                    // digit keypad[i][j] and of length k keypad[i][j]
                    // will become 1st digit, and we need to look for
                    // (k-1) more digits
                    num = keypad[i][j] - '0';
                    count[num][k] = 0;
  
                    // move left, up, right, down from current location
                    // and if new location is valid, then get number
                    // count of length (k-1) from that new digit and
                    // add in count we found so far
                    for (move=0; move<5; move++)
                    {
                        ro = i + row[move];
                        co = j + col[move];
                        if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
                           keypad[ro][co] != '*' && keypad[ro][co] != '#')
                        {
                            nextNum = keypad[ro][co] - '0';
                            count[num][k] += count[nextNum][k-1];
                        }
                    }
                }
            }
        }
    }
  
    // Get count of all possible numbers of length "n" starting
    // with digit 0, 1, 2, ..., 9
    totalCount = 0;
    for (i=0; i<=9; i++)
        totalCount += count[i][n];
    return totalCount;
}

23
Chapter 9. Mobile Numeric Keypad Problem

  
// Driver program to test above function
int main(int argc, char *argv[])
{
   char keypad[4][3] = {{'1','2','3'},
                        {'4','5','6'},
                        {'7','8','9'},
                        {'*','0','#'}};
   printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
   printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
   printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
   printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
   printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
  
   return 0;
}

Output:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

A Space Optimized Solution:


The above dynamic programming approach also runs in O(n) time and requires O(n) aux-
iliary space, as only one for loop runs n times, other for loops runs for constant time. We
can see that nth iteration needs data from (n-1)th iteration only, so we need not keep the
data from older iterations. We can have a space efficient dynamic programming approach
with just two arrays of size 10. Thanks to Nik for suggesting this solution.

// A Space Optimized C program to count number of possible numbers


// of given length
#include <stdio.h>
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    if(keypad == NULL || n <= 0)
        return 0;
    if(n == 1)
        return 10;
  
    // odd[i], even[i] arrays represent count of numbers starting
    // with digit i for any length j

24
Chapter 9. Mobile Numeric Keypad Problem

    int odd[10], even[10];


    int i = 0, j = 0, useOdd = 0, totalCount = 0;
  
    for (i=0; i<=9; i++)
        odd[i] = 1;  // for j = 1
  
    for (j=2; j<=n; j++) // Bottom Up calculation from j = 2 to n
    {
        useOdd = 1 - useOdd;
  
        // Here we are explicitly writing lines for each number 0
        // to 9. But it can always be written as DFS on 4X3 grid
        // using row, column array valid moves
        if(useOdd == 1)
        {
            even[0] = odd[0] + odd[8];
            even[1] = odd[1] + odd[2] + odd[4];
            even[2] = odd[2] + odd[1] + odd[3] + odd[5];
            even[3] = odd[3] + odd[2] + odd[6];
            even[4] = odd[4] + odd[1] + odd[5] + odd[7];
            even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6];
            even[6] = odd[6] + odd[3] + odd[5] + odd[9];
            even[7] = odd[7] + odd[4] + odd[8];
            even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9];
            even[9] = odd[9] + odd[6] + odd[8];
        }
        else
        {
            odd[0] = even[0] + even[8];
            odd[1] = even[1] + even[2] + even[4];
            odd[2] = even[2] + even[1] + even[3] + even[5];
            odd[3] = even[3] + even[2] + even[6];
            odd[4] = even[4] + even[1] + even[5] + even[7];
            odd[5] = even[5] + even[2] + even[4] + even[8] + even[6];
            odd[6] = even[6] + even[3] + even[5] + even[9];
            odd[7] = even[7] + even[4] + even[8];
            odd[8] = even[8] + even[0] + even[5] + even[7] + even[9];
            odd[9] = even[9] + even[6] + even[8];
        }
    }
  
    // Get count of all possible numbers of length "n" starting
    // with digit 0, 1, 2, ..., 9
    totalCount = 0;
    if(useOdd == 1)
    {
        for (i=0; i<=9; i++)
            totalCount += even[i];

25
Chapter 9. Mobile Numeric Keypad Problem

    }
    else
    {
        for (i=0; i<=9; i++)
            totalCount += odd[i];
    }
    return totalCount;
}
  
// Driver program to test above function
int main()
{
    char keypad[4][3] = {{'1','2','3'},
        {'4','5','6'},
        {'7','8','9'},
        {'*','0','#'}
    };
    printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
    printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
    printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
    printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
    printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
  
    return 0;
}

Output:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/mobile-numeric-keypad-problem/

26

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy