These 13 Infosys coding questions were shared by candidates after recent Infosys exams, including four from tests held in November 2026. Each one is written out in full: the problem, input and output format, constraints, two worked examples, the approach, and a tested solution in C++, Java and Python.

Table of Contents
Where These Questions Come From
Candidates shared these questions from memory after their Infosys tests, and four of them come from an Infosys SP exam set posted on Reddit (r/infosys). Because they were recalled, the wording, numbers and examples may not match the real paper word for word. Where a candidate’s memory had a gap, or an example did not follow its own rule, the question was rebuilt to be complete and consistent. Those questions are marked “reconstructed”, and a note under the example explains what changed.
Every solution reads from standard input and writes to standard output. All three versions run correctly on both examples shown here, and each was also checked against a brute-force answer on random tests.
Infosys Coding Questions at a Glance
| # | Question | Topic | Difficulty |
|---|---|---|---|
| 1 | Strip Cutting | Greedy, Sorting | Medium |
| 2 | Cards from Both Ends | Prefix Sum, Sliding Window | Medium |
| 3 | Gears on a Hilly Road | Dynamic Programming | Hard |
| 4 | Stone Path Across the Ponds | Grid DP | Hard |
| 5 | Last Exit Time | Greedy, Simulation | Medium |
| 6 | Garden with Tiles and Dominoes | DP, Fibonacci | Easy |
| 7 | Nurse Shift Rotation | Math, Modulo | Easy |
| 8 | Gears with Teeth | DP on Pairs | Hard |
| 9 | Painting Rooms | Greedy, Enumeration | Medium |
| 10 | Saplings and Pots | Greedy, Sorting, Two Pointers | Easy |
| 11 | Cafe Loyalty Stickers | Greedy, Sorting | Medium |
| 12 | Separated Domino Tiling | Profile DP, Matrix Exponentiation | Hard |
| 13 | Nurse Duty Roster | DP, Matrix Exponentiation | Complex |
How to Use This Practice Set
- Read the problem and the constraints, then try it yourself for 30 to 45 minutes before you open the approach.
- Look at the constraints first. Values up to 109 or 1018 need 64-bit integers (
long longin C++,longin Java). - Run your code on both examples, then on an edge case of your own, such as the smallest input or all equal values.
- Practise without autocomplete, so you are not slowed down by a basic editor in the test.
- Open the solution only in the language you plan to use in the exam, and compare it with yours line by line.
Question 1: Strip Cutting
Difficulty: Medium · Topic: Greedy, Sorting · Source: Infosys exam, shared by candidates
Problem
You are given N strips of ribbon. The length of the i-th strip is strips[i]. You are also given two integers K and L.
A cut splits one strip into two parts. You choose where to cut, but both parts must have a positive integer length. You can make at most K cuts in total across all strips, and pieces can never be joined back together.
Find the maximum number of pieces whose length is exactly L. A strip that is already of length L counts without any cut.
Input Format
- The first line contains three integers N, K and L.
- The second line contains N space-separated integers
strips[0] … strips[N-1].
Output Format
- Print one integer: the maximum number of pieces of length exactly L.
Constraints
- 1 ≤ N ≤ 105
- 0 ≤ K ≤ 109
- 1 ≤ L ≤ 109
- 1 ≤ strips[i] ≤ 109
Examples
Example 1
Input:
4 3 3
6 7 3 2
Output:
5
Explanation: The strip of length 3 already counts (1 piece). One cut on 6 gives 3 + 3 (2 pieces). Two cuts on 7 give 3 + 3 + 1 (2 pieces). That is 3 cuts and 1 + 2 + 2 = 5 pieces. The strip of length 2 is too short.
Example 2
Input:
5 2 4
8 4 12 5 3
Output:
4
Explanation: The strip 4 counts as it is. One cut on 8 gives 4 + 4 and one cut on 5 gives 4 + 1. With only 2 cuts the best total is 1 + 2 + 1 = 4.
Approach
- A strip of length x can give at most
q = x / Lpieces. If x is a multiple of L it needs onlyq − 1cuts (the last part is automatically L); otherwise it needsqcuts. - Every useful cut produces one L-piece. Fully finishing a multiple-of-L strip gives one bonus piece for free.
- So the answer is: strips already equal to L +
min(K, total useful cuts)+ the number of multiple-of-L strips we can finish completely. - To finish as many as possible, sort those strips by the cuts they need and take the cheapest first (greedy).
Complexity: Time: O(N log N) · Space: O(N)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k, L;
cin >> n >> k >> L;
long long ready = 0, capacity = 0;
vector<long long> finish;
for (int i = 0; i < n; i++) {
long long x; cin >> x;
long long q = x / L;
if (q == 0) continue;
if (x % L == 0) {
if (q == 1) ready++;
else { capacity += q - 1; finish.push_back(q - 1); }
} else capacity += q;
}
sort(finish.begin(), finish.end());
long long used = 0, bonus = 0;
for (long long c : finish) {
if (used + c > k) break;
used += c; bonus++;
}
cout << ready + min(k, capacity) + bonus << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int n = (int) in.nval;
in.nextToken(); long k = (long) in.nval;
in.nextToken(); long L = (long) in.nval;
long ready = 0, capacity = 0;
List<Long> finish = new ArrayList<>();
for (int i = 0; i < n; i++) {
in.nextToken(); long x = (long) in.nval;
long q = x / L;
if (q == 0) continue;
if (x % L == 0) {
if (q == 1) ready++;
else { capacity += q - 1; finish.add(q - 1); }
} else capacity += q;
}
Collections.sort(finish);
long used = 0, bonus = 0;
for (long c : finish) {
if (used + c > k) break;
used += c; bonus++;
}
System.out.println(ready + Math.min(k, capacity) + bonus);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
n, k, L = int(data[0]), int(data[1]), int(data[2])
strips = list(map(int, data[3:3 + n]))
ready = 0 # strips that are already exactly L (need 0 cuts)
capacity = 0 # how many cuts can each produce one L-piece
finish = [] # cuts needed to fully cut a strip whose length is a multiple of L
for x in strips:
q = x // L
if q == 0:
continue
if x % L == 0:
if q == 1:
ready += 1
else:
capacity += q - 1
finish.append(q - 1)
else:
capacity += q
# every useful cut gives one piece; fully cutting a multiple-of-L strip gives one bonus piece
finish.sort()
used = bonus = 0
for c in finish:
if used + c > k:
break
used += c
bonus += 1
print(ready + min(k, capacity) + bonus)
main()
Question 2: Cards from Both Ends
Difficulty: Medium · Topic: Prefix Sum, Sliding Window · Source: Infosys exam, shared by candidates
Problem
There are N cards in a row, and the i-th card has value cards[i] (values can be negative). You are also given two integers K and R.
You must take exactly K cards, one at a time. Each time you take the card at the current left end or the current right end of the row. At most R of the K cards may come from the right end.
Find the maximum possible sum of the cards you take.
Input Format
- The first line contains three integers N, K and R.
- The second line contains N space-separated integers
cards[0] … cards[N-1].
Output Format
- Print one integer: the maximum sum.
Constraints
- 1 ≤ K ≤ N ≤ 105
- 0 ≤ R ≤ N
- −104 ≤ cards[i] ≤ 104
Examples
Example 1
Input:
7 3 1
1 2 3 4 5 6 9
Output:
12
Explanation: Take 1 and 2 from the left and 9 from the right: 1 + 2 + 9 = 12. Taking 6 as well is not allowed because only R = 1 card may come from the right.
Example 2
Input:
6 4 2
9 -2 1 3 7 8
Output:
22
Explanation: Take 9, −2 from the left and 8, 7 from the right: 9 − 2 + 8 + 7 = 22.
Approach
- The order of picks does not matter. Only how many come from the right matters: if t cards come from the right, the first K − t cards come from the left.
- Start with all K cards from the left. Then, for t = 1 … min(K, R), drop card
K − tfrom the left sum and add cardN − tto the right sum. - The answer is the best (left + right) value seen.
Complexity: Time: O(N) · Space: O(N)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, r;
cin >> n >> k >> r;
vector<long long> a(n);
for (auto &x : a) cin >> x;
long long left = 0;
for (int i = 0; i < k; i++) left += a[i]; // all k from the left
long long best = left, right = 0;
for (int t = 1; t <= min(k, r); t++) { // t cards from the right
left -= a[k - t];
right += a[n - t];
best = max(best, left + right);
}
cout << best << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int n = (int) in.nval;
in.nextToken(); int k = (int) in.nval;
in.nextToken(); int r = (int) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) { in.nextToken(); a[i] = (long) in.nval; }
long left = 0;
for (int i = 0; i < k; i++) left += a[i];
long best = left, right = 0;
for (int t = 1; t <= Math.min(k, r); t++) {
left -= a[k - t];
right += a[n - t];
best = Math.max(best, left + right);
}
System.out.println(best);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
n, k, r = int(data[0]), int(data[1]), int(data[2])
a = list(map(int, data[3:3 + n]))
left = sum(a[:k]) # take all k cards from the left
best = left
right = 0
for t in range(1, min(k, r) + 1): # t cards from the right
left -= a[k - t]
right += a[n - t]
best = max(best, left + right)
print(best)
main()
Question 3: Gears on a Hilly Road
Difficulty: Hard · Topic: Dynamic Programming · Source: Infosys exam, shared by candidates
Problem
A cyclist rides N road segments in order. Segment i is given as segments[i] = [slope, length]. The bicycle has G gears numbered 1 to G, and a gear-change factor S is given.
- Riding segment i in gear g costs
|slope − g| × length. - Changing from gear g to gear g′ costs
S × |g − g′|. - Gears can be changed only between segments, never in the middle of one.
- The starting gear can be chosen freely (no cost).
Find the minimum total cost to ride all segments.
Input Format
- The first line contains three integers N, G and S.
- Each of the next N lines contains two integers:
slopeandlengthof a segment.
Output Format
- Print one integer: the minimum total cost.
Constraints
- 1 ≤ N ≤ 1000
- 1 ≤ G ≤ 1000
- 0 ≤ S ≤ 104
- 0 ≤ slope ≤ 104
- 1 ≤ length ≤ 104
- Use 64-bit integers for the cost
Examples
Example 1
Input:
3 5 2
3 4
1 2
5 3
Output:
8
Explanation: Use gears 3, 3, 5. Segment 1 costs 0, segment 2 costs |1 − 3| × 2 = 4, the change 3 → 5 costs 2 × 2 = 4, and segment 3 costs 0. Total = 8.
Example 2
Input:
2 3 10
1 5
3 5
Output:
10
Explanation: Changing gears is expensive here. Staying in gear 1 costs 0 + |3 − 1| × 5 = 10, while switching to gear 3 costs 10 × 2 = 20.
Approach
dp[i][g]= minimum cost after riding segment i in gear g. For the first segment,dp[0][g] = |slope₀ − g| × length₀.- Transition:
dp[i][g] = min over g′ ( dp[i−1][g′] + S × |g − g′| ) + |slope − g| × length. - The inner minimum would be O(G²). Compute it in O(G) with two passes: left-to-right
best[g] = min(best[g], best[g−1] + S)and right-to-leftbest[g] = min(best[g], best[g+1] + S). - The answer is the minimum of the last row.
Complexity: Time: O(N × G) · Space: O(G)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, G; long long s;
cin >> n >> G >> s;
vector<long long> slope(n), len(n);
for (int i = 0; i < n; i++) cin >> slope[i] >> len[i];
vector<long long> dp(G + 1), best(G + 1);
for (int g = 1; g <= G; g++) dp[g] = llabs(slope[0] - g) * len[0];
for (int i = 1; i < n; i++) {
best = dp;
for (int g = 2; g <= G; g++) best[g] = min(best[g], best[g - 1] + s);
for (int g = G - 1; g >= 1; g--) best[g] = min(best[g], best[g + 1] + s);
for (int g = 1; g <= G; g++) dp[g] = best[g] + llabs(slope[i] - g) * len[i];
}
cout << *min_element(dp.begin() + 1, dp.end()) << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int n = (int) in.nval;
in.nextToken(); int G = (int) in.nval;
in.nextToken(); long s = (long) in.nval;
long[] slope = new long[n], len = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken(); slope[i] = (long) in.nval;
in.nextToken(); len[i] = (long) in.nval;
}
long[] dp = new long[G + 1];
for (int g = 1; g <= G; g++) dp[g] = Math.abs(slope[0] - g) * len[0];
for (int i = 1; i < n; i++) {
long[] best = dp.clone();
for (int g = 2; g <= G; g++) best[g] = Math.min(best[g], best[g - 1] + s);
for (int g = G - 1; g >= 1; g--) best[g] = Math.min(best[g], best[g + 1] + s);
for (int g = 1; g <= G; g++) dp[g] = best[g] + Math.abs(slope[i] - g) * len[i];
}
long ans = Long.MAX_VALUE;
for (int g = 1; g <= G; g++) ans = Math.min(ans, dp[g]);
System.out.println(ans);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
n, G, s = int(data[0]), int(data[1]), int(data[2])
seg = [(int(data[3 + 2 * i]), int(data[4 + 2 * i])) for i in range(n)]
# dp[g] = minimum cost after riding the current segment in gear g (index 0 -> gear 1)
slope, length = seg[0]
dp = [abs(slope - g) * length for g in range(1, G + 1)]
for i in range(1, n):
# best[g] = min over g' of dp[g'] + s*|g - g'| (two linear passes)
best = dp[:]
for g in range(1, G):
best[g] = min(best[g], best[g - 1] + s)
for g in range(G - 2, -1, -1):
best[g] = min(best[g], best[g + 1] + s)
slope, length = seg[i]
dp = [best[g - 1] + abs(slope - g) * length for g in range(1, G + 1)]
print(min(dp))
main()
Question 4: Stone Path Across the Ponds
Difficulty: Hard · Topic: Grid DP · Source: Infosys exam, shared by candidates (reconstructed from memory)
Problem
A pond is an M × N grid of stepping stones. Every cell holds a stone described by three integers [stone, color, cost], and an integer D is given.
You start on any stone of the first row and must reach any stone of the last (M-th) row. In one jump you move from a stone in row i to any stone in row i + 1 (any column). A jump from stone A to stone B is allowed only when:
|A.stone − B.stone| < D, andA.color ≠ B.color(you cannot step down onto the same color).
The total cost of a path is the sum of the costs of all stones you stand on, including the first and the last. Find the minimum total cost, or print −1 if the last row cannot be reached.
Input Format
- The first line contains three integers M, N and D.
- Each of the next M lines contains 3 × N integers:
stone color costfor every column of that row, left to right.
Output Format
- Print one integer: the minimum cost, or −1 if it is impossible.
Constraints
- 1 ≤ D ≤ 109
- 1 ≤ M, N ≤ 100
- 1 ≤ stone, color, cost ≤ 109
- Use 64-bit integers for the cost
Examples
Example 1
Input:
3 3 3
1 1 5 4 2 2 6 1 9
2 2 4 5 1 1 3 1 2
4 1 3 1 2 6 2 2 1
Output:
5
Explanation: Start on (4, color 2, cost 2) in row 1. Jump to (3, color 1, cost 2) in row 2: |4 − 3| = 1 < 3 and the colors differ. Jump to (2, color 2, cost 1) in row 3: |3 − 2| = 1 < 3 and the colors differ. Total = 2 + 2 + 1 = 5.
Example 2
Input:
2 2 2
1 1 5 3 1 4
6 2 1 8 1 2
Output:
-1
Explanation: Every stone in row 2 differs by at least 3 from every stone in row 1, so no jump satisfies |difference| < 2. The answer is −1.
Approach
dp[r][j]= minimum cost of a path that ends on stone j of row r. Row 1:dp[0][j] = costof that stone.- For every stone j in row r, look at every stone p of row r − 1 that can jump to it (difference < D and different color) and take
min(dp[r−1][p]) + cost[r][j]. - Unreachable stones keep the value ∞. The answer is the minimum of the last row, or −1 if all are ∞.
Complexity: Time: O(M × N²) · Space: O(N)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int m, n; long long d;
cin >> m >> n >> d;
vector<vector<array<long long, 3>>> g(m, vector<array<long long, 3>>(n));
for (auto &row : g) for (auto &c : row) cin >> c[0] >> c[1] >> c[2];
const long long INF = LLONG_MAX;
vector<long long> dp(n), nd(n);
for (int j = 0; j < n; j++) dp[j] = g[0][j][2];
for (int r = 1; r < m; r++) {
for (int j = 0; j < n; j++) {
long long best = INF;
for (int p = 0; p < n; p++)
if (dp[p] < best && llabs(g[r - 1][p][0] - g[r][j][0]) < d && g[r - 1][p][1] != g[r][j][1])
best = dp[p];
nd[j] = best == INF ? INF : best + g[r][j][2];
}
swap(dp, nd);
}
long long ans = *min_element(dp.begin(), dp.end());
cout << (ans == INF ? -1 : ans) << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int m = (int) in.nval;
in.nextToken(); int n = (int) in.nval;
in.nextToken(); long d = (long) in.nval;
long[][] stone = new long[m][n], color = new long[m][n], cost = new long[m][n];
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++) {
in.nextToken(); stone[r][c] = (long) in.nval;
in.nextToken(); color[r][c] = (long) in.nval;
in.nextToken(); cost[r][c] = (long) in.nval;
}
final long INF = Long.MAX_VALUE;
long[] dp = new long[n];
for (int j = 0; j < n; j++) dp[j] = cost[0][j];
for (int r = 1; r < m; r++) {
long[] nd = new long[n];
for (int j = 0; j < n; j++) {
long best = INF;
for (int p = 0; p < n; p++)
if (dp[p] < best && Math.abs(stone[r - 1][p] - stone[r][j]) < d && color[r - 1][p] != color[r][j])
best = dp[p];
nd[j] = best == INF ? INF : best + cost[r][j];
}
dp = nd;
}
long ans = INF;
for (long v : dp) ans = Math.min(ans, v);
System.out.println(ans == INF ? -1 : ans);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
m, n, d = int(data[0]), int(data[1]), int(data[2])
vals = list(map(int, data[3:]))
grid = [[tuple(vals[(r * n + c) * 3:(r * n + c) * 3 + 3]) for c in range(n)] for r in range(m)]
INF = float('inf')
dp = [cell[2] for cell in grid[0]] # start anywhere in row 1, pay that stone's cost
for r in range(1, m):
nd = [INF] * n
for j, (stone, color, cost) in enumerate(grid[r]):
best = INF
for p, (ps, pc, _) in enumerate(grid[r - 1]):
if dp[p] < best and abs(ps - stone) < d and pc != color:
best = dp[p]
if best < INF:
nd[j] = best + cost
dp = nd
ans = min(dp)
print(-1 if ans == INF else ans)
main()
Question 5: Last Exit Time
Difficulty: Medium · Topic: Greedy, Simulation · Source: Infosys exam, shared by candidates
Problem
A shopping mall has N checkout lanes. Lane i has:
delay[i]: the time at which the lane first becomes available,speed[i]: the number of items it processes per second,isQuick[i]: 1 for a quick lane, 0 for a normal lane.
M shoppers are waiting, and shopper j carries items[j] items. A quick lane can serve only shoppers whose item count is at most K. A normal lane can serve anyone.
Rules of the checkout:
- Shoppers are served in the given order. When it is a shopper’s turn, they join the eligible lane where they would leave the earliest. If two lanes tie, the lane with the smaller index is chosen.
- Each lane serves one shopper at a time. A shopper with
xitems needs⌈x / speed⌉seconds, starting when the lane is free.
Find the time at which the last shopper leaves the mall. Print −1 if some shopper cannot use any lane.
Input Format
- The first line contains an integer N.
- Each of the next N lines contains three integers:
delay[i] speed[i] isQuick[i]. - The next line contains an integer M.
- The next line contains M space-separated integers:
items[0] … items[M-1]. - The last line contains an integer K.
Output Format
- Print one integer: the time the last shopper leaves, or −1.
Constraints
- 0 ≤ delay[i] ≤ 109
- 1 ≤ N, M ≤ 1000
- 1 ≤ speed[i] ≤ 109
- 1 ≤ items[j], K ≤ 109
Examples
Example 1
Input:
3
0 2 0
2 1 1
1 3 0
4
5 2 8 3
3
Output:
5
Explanation: Lanes: L1 (free at 0, speed 2, normal), L2 (free at 2, speed 1, quick), L3 (free at 1, speed 3, normal), K = 3.
- 5 items (too many for L2): L1 → 0 + 3 = 3, L3 → 1 + 2 = 3; tie, so L1. L1 is now free at 3.
- 2 items: L1 → 4, L2 → 4, L3 → 1 + 1 = 2. L3 is chosen, free at 2.
- 8 items: L1 → 3 + 4 = 7, L3 → 2 + 3 = 5. L3 is chosen, free at 5.
- 3 items: L1 → 3 + 2 = 5, L2 → 2 + 3 = 5, L3 → 6. L1 is chosen and leaves at 5. The last shopper leaves at time 5.
Example 2
Input:
2
0 5 1
1 2 1
3
2 4 1
3
Output:
-1
Explanation: Both lanes are quick lanes and K = 3, so the shopper with 4 items cannot use any lane. The answer is −1.
Approach
- Keep
free[i], the time at which lane i is next available (initiallydelay[i]). - For each shopper in order, check every eligible lane and compute
free[i] + ⌈items / speed[i]⌉. Pick the smallest (smaller index on a tie). - Update that lane’s free time, and keep the maximum finish time as the answer. If no lane is eligible, print −1.
Complexity: Time: O(N × M) · Space: O(N)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
vector<long long> freeAt(n), speed(n); vector<int> quick(n);
for (int i = 0; i < n; i++) cin >> freeAt[i] >> speed[i] >> quick[i];
int m; cin >> m;
vector<long long> items(m);
for (auto &x : items) cin >> x;
long long k; cin >> k;
long long last = 0;
for (long long it : items) { // shoppers in the given order
int lane = -1; long long best = 0;
for (int i = 0; i < n; i++) {
if (quick[i] == 1 && it > k) continue;
long long finish = freeAt[i] + (it + speed[i] - 1) / speed[i];
if (lane == -1 || finish < best) { best = finish; lane = i; }
}
if (lane == -1) { cout << -1 << "\n"; return 0; }
freeAt[lane] = best;
last = max(last, best);
}
cout << last << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int n = (int) in.nval;
long[] freeAt = new long[n], speed = new long[n]; int[] quick = new int[n];
for (int i = 0; i < n; i++) {
in.nextToken(); freeAt[i] = (long) in.nval;
in.nextToken(); speed[i] = (long) in.nval;
in.nextToken(); quick[i] = (int) in.nval;
}
in.nextToken(); int m = (int) in.nval;
long[] items = new long[m];
for (int i = 0; i < m; i++) { in.nextToken(); items[i] = (long) in.nval; }
in.nextToken(); long k = (long) in.nval;
long last = 0;
for (long it : items) {
int lane = -1; long best = 0;
for (int i = 0; i < n; i++) {
if (quick[i] == 1 && it > k) continue;
long finish = freeAt[i] + (it + speed[i] - 1) / speed[i];
if (lane == -1 || finish < best) { best = finish; lane = i; }
}
if (lane == -1) { System.out.println(-1); return; }
freeAt[lane] = best;
last = Math.max(last, best);
}
System.out.println(last);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
pos = 0
n = int(data[pos]); pos += 1
free, speed, quick = [], [], []
for _ in range(n):
free.append(int(data[pos])); speed.append(int(data[pos + 1])); quick.append(int(data[pos + 2])); pos += 3
m = int(data[pos]); pos += 1
items = list(map(int, data[pos:pos + m])); pos += m
k = int(data[pos])
last = 0
for it in items: # shoppers are served in the given order
best, lane = None, -1
for i in range(n):
if quick[i] == 1 and it > k: # quick lane cannot take this shopper
continue
finish = free[i] + (it + speed[i] - 1) // speed[i]
if best is None or finish < best:
best, lane = finish, i
if lane == -1:
print(-1)
return
free[lane] = best
last = max(last, best)
print(last)
main()
Question 6: Garden with Tiles and Dominoes
Difficulty: Easy · Topic: DP, Fibonacci · Source: Infosys SP exam set shared on Reddit (r/infosys)
Problem
A garden is a single row of N cells. You must cover every cell exactly once, using:
- a tile, which covers 1 cell, or
- a domino, which covers 2 adjacent cells.
Find the number of different ways to cover the whole garden. Two ways are different if the sequence of tiles and dominoes from left to right is different. Since the answer can be large, print it modulo 109 + 7.
Input Format
- A single integer N.
Output Format
- Print the number of ways modulo 109 + 7.
Constraints
- 1 ≤ N ≤ 106
Examples
Example 1
Input:
4
Output:
5
Explanation: The 5 ways (T = tile, D = domino): T T T T, D T T, T D T, T T D, D D.
Example 2
Input:
6
Output:
13
Explanation: ways(5) = 8 and ways(4) = 5, so ways(6) = 8 + 5 = 13.
Approach
- Look at the first cell: it is covered by a tile (then N − 1 cells remain) or by a domino (then N − 2 cells remain).
- So
ways(N) = ways(N − 1) + ways(N − 2), withways(0) = ways(1) = 1. These are the Fibonacci numbers. - Keep only the last two values and take the modulo at every step.
Complexity: Time: O(N) · Space: O(1)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
const long long MOD = 1000000007LL;
long long n; cin >> n;
long long a = 1, b = 1; // ways(0), ways(1)
for (long long i = 2; i <= n; i++) { long long c = (a + b) % MOD; a = b; b = c; }
cout << b << "\n";
return 0;
}
Show the Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
final long MOD = 1_000_000_007L;
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long a = 1, b = 1; // ways(0), ways(1)
for (long i = 2; i <= n; i++) { long c = (a + b) % MOD; a = b; b = c; }
System.out.println(b);
}
}
Show the Python solution
import sys
MOD = 10**9 + 7
def main():
n = int(sys.stdin.read().split()[0])
a, b = 1, 1 # ways(0) = 1, ways(1) = 1
for _ in range(n - 1):
a, b = b, (a + b) % MOD # ways(i) = ways(i-1) + ways(i-2)
print(b)
main()
Question 7: Nurse Shift Rotation
Difficulty: Easy · Topic: Math, Modulo · Source: Infosys SP exam set shared on Reddit (r/infosys)
Problem
There are N nurses in a hospital, and each nurse has a shift on day 1. Every day each nurse moves to the next shift in this fixed cycle:
Day → Night → Off → Day → …
Given the shifts on day 1 and an integer D, print the shift of every nurse on day D.
Input Format
- The first line contains two integers N and D.
- The second line contains N words, each one of
Day,NightorOff.
Output Format
- Print N words separated by spaces: each nurse’s shift on day D.
Constraints
- 1 ≤ N ≤ 105
- 1 ≤ D ≤ 1018
Examples
Example 1
Input:
3 2
Day Night Off
Output:
Night Off Day
Explanation: On day 2 every nurse has moved one step: Day → Night, Night → Off, Off → Day.
Example 2
Input:
4 5
Off Day Day Night
Output:
Day Night Night Off
Explanation: Day 5 is 4 steps after day 1. The cycle repeats every 3 days, so 4 steps equal 1 step.
Note: In the original picture D = 2 gives a single step (Day → Night), so the given shifts are taken as the shifts on day 1. This makes the example consistent.
Approach
- From day 1 to day D the shift moves
D − 1times. Because the cycle has length 3, only(D − 1) mod 3steps matter. - Map Day → 0, Night → 1, Off → 2, add the step count, take mod 3 and map back.
- D can be huge, so never simulate the days one by one.
Complexity: Time: O(N) · Space: O(1) extra
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, d;
cin >> n >> d;
vector<string> order = {"Day", "Night", "Off"};
int shift = (int)((d - 1) % 3); // shifts given are for day 1
for (long long i = 0; i < n; i++) {
string s; cin >> s;
int idx = find(order.begin(), order.end(), s) - order.begin();
cout << order[(idx + shift) % 3] << (i + 1 < n ? " " : "\n");
}
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long d = Long.parseLong(st.nextToken());
List<String> order = Arrays.asList("Day", "Night", "Off");
int shift = (int) ((d - 1) % 3);
StringBuilder sb = new StringBuilder();
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
int idx = order.indexOf(st.nextToken());
sb.append(order.get((idx + shift) % 3)).append(i + 1 < n ? " " : "");
}
System.out.println(sb);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
n, d = int(data[0]), int(data[1])
order = ["Day", "Night", "Off"]
idx = {s: i for i, s in enumerate(order)}
shift = (d - 1) % 3 # given shifts are for day 1; the cycle repeats every 3 days
print(" ".join(order[(idx[w] + shift) % 3] for w in data[2:2 + n]))
main()
Question 8: Gears with Teeth
Difficulty: Hard · Topic: DP on Pairs · Source: Infosys SP exam set shared on Reddit (r/infosys)
Problem
You have N gears; gear i has i teeth (1 ≤ i ≤ N), and each gear can be used at most once. Arrange some of them in a chain g₁ → g₂ → … → gₖ where every next gear has fewer teeth than the previous one.
The ratio of a consecutive pair is gᵢ / gᵢ₊₁. The chain is valid if these ratios are strictly decreasing: g₁/g₂ > g₂/g₃ > … > gₖ₋₁/gₖ. A single gear, or any two gears, form a valid chain.
Find the maximum number of gears in a valid chain.
Input Format
- A single integer N.
Output Format
- Print the maximum chain length.
Constraints
- 1 ≤ N ≤ 1000
Examples
Example 1
Input:
5
Output:
3
Explanation: One valid chain is 5 → 3 → 2: ratios 5/3 ≈ 1.67 > 3/2 = 1.5. No chain of 4 gears exists with only 5 gears.
Example 2
Input:
9
Output:
4
Explanation: 9 → 5 → 3 → 2 has ratios 1.8 > 1.67 > 1.5, so the answer is 4.
Note: The example in the original picture (5 → 3 → 1) does not follow its own rule: its ratios 5/3 and 3/1 increase. With strictly decreasing ratios the answer 3 for N = 5 is still correct, using the chain 5 → 3 → 2.
Approach
- A chain is fixed by its last two gears, so let
f[i][j](i > j) be the longest valid chain ending with i → j. - Gear h can come right before i → j when h/i > i/j, which is
h × j > i², i.e.h ≥ ⌊i² / j⌋ + 1. Sof[i][j] = 1 + max f[h][i]over those h (or 2 if none). - Process i from N down to 1 and keep a suffix maximum of
f[h][i]over h. Each state is then O(1).
Complexity: Time: O(N²) · Space: O(N²)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
// f[i][j] (i > j): longest chain ending with i -> j
vector<vector<int>> f(n + 1);
vector<int> suf(n + 2);
int best = 1;
for (int i = n; i >= 1; i--) {
suf[n + 1] = 0;
for (int h = n; h > i; h--) suf[h] = max(suf[h + 1], f[h][i]);
f[i].assign(i, 0);
for (int j = 1; j < i; j++) {
long long t = 1LL * i * i / j + 1; // h must satisfy h*j > i*i
f[i][j] = (t <= n && suf[t]) ? 1 + suf[t] : 2;
best = max(best, f[i][j]);
}
}
cout << best << "\n";
return 0;
}
Show the Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] f = new int[n + 1][];
int[] suf = new int[n + 2];
int best = 1;
for (int i = n; i >= 1; i--) {
suf[n + 1] = 0;
for (int h = n; h > i; h--) suf[h] = Math.max(suf[h + 1], f[h][i]);
f[i] = new int[i];
for (int j = 1; j < i; j++) {
long t = (long) i * i / j + 1;
f[i][j] = (t <= n && suf[(int) t] > 0) ? 1 + suf[(int) t] : 2;
best = Math.max(best, f[i][j]);
}
}
System.out.println(best);
}
}
Show the Python solution
import sys
def main():
n = int(sys.stdin.read().split()[0])
# f[i][j] (i > j) = longest chain ending with the pair i -> j.
# Gear h may come right before i -> j when h/i > i/j, i.e. h*j > i*i, i.e. h >= i*i//j + 1.
f = [None] * (n + 1)
best = 1
for i in range(n, 0, -1): # gears bigger than i are processed first
suf = [0] * (n + 2) # suf[h] = max f[x][i] over x >= h
for h in range(n, i, -1):
suf[h] = max(suf[h + 1], f[h][i])
row = [0] * i
for j in range(1, i):
t = i * i // j + 1
row[j] = 1 + suf[t] if t <= n and suf[t] else 2
best = max(best, row[j])
f[i] = row
print(best)
main()
Question 9: Painting Rooms
Difficulty: Medium · Topic: Greedy, Enumeration · Source: Infosys SP exam set shared on Reddit (r/infosys)
Problem
You have to paint R rooms; room i needs paint[i] litres. Paint is sold in two kinds of boxes:
- Small box: S litres, costs Cs.
- Large box: L litres, costs Cl.
You can buy any number of boxes of each kind. Every room is painted from its own boxes: leftover paint from one room cannot be used for another. Find the minimum total cost to paint all rooms.
Input Format
- The first line contains an integer R.
- The second line contains R integers:
paint[0] … paint[R-1]. - The third line contains two integers S and Cs.
- The fourth line contains two integers L and Cl.
Output Format
- Print one integer: the minimum total cost.
Constraints
- 1 ≤ R ≤ 1000
- 1 ≤ paint[i] ≤ 1000
- 1 ≤ S, L ≤ 1000
- 1 ≤ Cs, Cl ≤ 106
Examples
Example 1
Input:
3
3 4 6
2 100
5 220
Output:
700
Explanation: 3 L: 2 small boxes = 200 (1 large = 220). 4 L: 2 small = 200. 6 L: 3 small = 300, which is cheaper than 1 large + 1 small = 320. Total = 200 + 200 + 300 = 700.
Example 2
Input:
2
7 10
3 50
4 60
Output:
270
Explanation: 7 L: 1 large + 1 small = 110. 10 L: 1 large + 2 small = 160. Total = 270.
Note: The original picture shows 720 for this example, but its plan for the 6-litre room (1 large + 1 small = 320) is not the cheapest: 3 small boxes cost 300. The correct minimum is 700.
Approach
- Rooms are independent, so solve each room separately and add the costs.
- For one room, try every number of large boxes x from 0 to ⌈need / L⌉. The rest
max(0, need − x·L)is covered by⌈rest / S⌉small boxes. - Keep the cheapest combination for that room.
Complexity: Time: O(R × max(paint) / L) · Space: O(1) extra
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int r; cin >> r;
vector<long long> rooms(r);
for (auto &x : rooms) cin >> x;
long long S, Cs, L, Cl;
cin >> S >> Cs >> L >> Cl;
long long total = 0;
for (long long need : rooms) {
long long best = LLONG_MAX;
for (long long large = 0; large <= (need + L - 1) / L; large++) {
long long rest = max(0LL, need - large * L);
best = min(best, large * Cl + (rest + S - 1) / S * Cs);
}
total += best;
}
cout << total << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken(); int r = (int) in.nval;
long[] rooms = new long[r];
for (int i = 0; i < r; i++) { in.nextToken(); rooms[i] = (long) in.nval; }
in.nextToken(); long S = (long) in.nval;
in.nextToken(); long Cs = (long) in.nval;
in.nextToken(); long L = (long) in.nval;
in.nextToken(); long Cl = (long) in.nval;
long total = 0;
for (long need : rooms) {
long best = Long.MAX_VALUE;
for (long large = 0; large <= (need + L - 1) / L; large++) {
long rest = Math.max(0, need - large * L);
best = Math.min(best, large * Cl + (rest + S - 1) / S * Cs);
}
total += best;
}
System.out.println(total);
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.read().split()
r = int(data[0])
rooms = list(map(int, data[1:1 + r]))
S, Cs, L, Cl = map(int, data[1 + r:5 + r])
total = 0
for need in rooms:
best = None
# try every possible number of large boxes; the rest is covered by small boxes
for large in range((need + L - 1) // L + 1):
rest = max(0, need - large * L)
cost = large * Cl + ((rest + S - 1) // S) * Cs
if best is None or cost < best:
best = cost
total += best
print(total)
main()
Question 10: Saplings and Pots
Difficulty: Easy · Topic: Greedy, Sorting, Two Pointers · Source: Infosys exam, Nov 2026, shared by candidates
Problem
A nursery has n saplings and m pots. The array root gives the root width of each sapling, and the array pot gives the width of each pot.
A sapling with root width r can be planted in a pot of width w only if r ≤ w ≤ 2 × r — the pot must be at least as wide as the roots, but not more than twice as wide.
Each pot can hold at most one sapling, and each sapling goes into at most one pot. Find the maximum number of saplings that can be potted.
Input Format
- The first line contains two integers n and m.
- The second line contains n integers:
root[0] … root[n-1]. - The third line contains m integers:
pot[0] … pot[m-1].
Output Format
- Print one integer: the maximum number of saplings that can be potted.
Constraints
- 1 ≤ n, m ≤ 105
- 1 ≤ root[i], pot[j] ≤ 109
Examples
Example 1
Input:
3 4
2 5 10
3 4 11 25
Output:
2
Explanation: Sapling 2 fits pots of width 2 … 4, so it takes pot 3. Sapling 10 fits pots 10 … 20, so it takes pot 11. Sapling 5 needs a pot of width 5 … 10 and none is left. Answer 2.
Example 2
Input:
4 3
1 1 6 7
2 3 13
Output:
2
Explanation: One sapling of width 1 takes pot 2 (the other 1 has no pot of width 1 … 2 left). Sapling 6 fits 6 … 12 — no pot. Sapling 7 fits 7 … 14 and takes pot 13. Answer 2.
Approach
- Each sapling accepts an interval of pot widths:
[r, 2r]. Sort the saplings by r; then the right ends 2r are sorted too. - Sort the pots and go through them from the smallest. Skip saplings whose interval already ended (
2r < w) — no later, wider pot can help them. - If the smallest remaining sapling has
r ≤ w, plant it in this pot. Giving each pot to the sapling whose interval ends first is the classic optimal greedy. - Use 64-bit values for
2 × r(up to 2·109).
Complexity: Time: O(n log n + m log m) · Space: O(1) extra
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<long long> root(n), pot(m);
for (auto &x : root) cin >> x;
for (auto &x : pot) cin >> x;
sort(root.begin(), root.end());
sort(pot.begin(), pot.end());
// sapling i accepts pots in [root[i], 2*root[i]]; give each pot (smallest first)
// to the smallest sapling that can still use it
int i = 0; long long count = 0;
for (long long p : pot) {
while (i < n && 2 * root[i] < p) i++; // too small for this pot and all later pots
if (i < n && root[i] <= p) { count++; i++; }
}
cout << count << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(System.in, 1 << 16));
int n = (int) readLong(in), m = (int) readLong(in);
long[] root = new long[n], pot = new long[m];
for (int i = 0; i < n; i++) root[i] = readLong(in);
for (int j = 0; j < m; j++) pot[j] = readLong(in);
Arrays.sort(root);
Arrays.sort(pot);
int i = 0; long count = 0;
for (long p : pot) {
while (i < n && 2 * root[i] < p) i++; // too small for this pot and all later pots
if (i < n && root[i] <= p) { count++; i++; }
}
System.out.println(count);
}
static long readLong(DataInputStream in) throws IOException { // fast reader for 2*10^5 numbers
int b = in.read();
while (b != '-' && (b < '0' || b > '9')) b = in.read();
boolean neg = b == '-';
if (neg) b = in.read();
long r = 0;
while (b >= '0' && b <= '9') { r = r * 10 + (b - '0'); b = in.read(); }
return neg ? -r : r;
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.buffer.read().split()
n, m = int(data[0]), int(data[1])
root = sorted(map(int, data[2:2 + n]))
pot = sorted(map(int, data[2 + n:2 + n + m]))
# Sapling i accepts pots in [root[i], 2*root[i]]. Sorted by root, these ranges are also
# sorted by their right end, so each pot (smallest first) goes to the smallest sapling
# that can still use it.
i = count = 0
for p in pot:
while i < n and 2 * root[i] < p: # too small for this pot and every later pot
i += 1
if i < n and root[i] <= p:
count += 1
i += 1
print(count)
main()
Question 11: Cafe Loyalty Stickers
Difficulty: Medium · Topic: Greedy, Sorting · Source: Infosys exam, Nov 2026, shared by candidates
Problem
A cafe runs a loyalty card. There are N customers; customer i is described by two numbers: stickers[i], the stickers already on their card, and limit[i], the maximum number of bonus stickers that customer can be given.
A customer gets a free coffee once their card has at least R stickers. The cafe has B bonus stickers in total to hand out. A bonus sticker given to a customer stays on that customer’s card, and nobody may receive more than their own limit.
Distribute the bonus stickers to maximise the number of customers who get a free coffee (customers who already have R or more stickers count without any bonus).
Input Format
- Line 1: three numbers separated by spaces. N is how many customers there are, R is the number of stickers needed for one free coffee, and B is the total number of bonus stickers the cafe can give away.
- Lines 2 to N + 1: one customer per line, written as two numbers. First comes
stickers[i], the stickers already on that card, thenlimit[i], the most bonus stickers that customer is allowed to receive.
Output Format
- A single number: the highest count of customers who can end up with a free coffee.
Constraints
- 1 ≤ N ≤ 105
- 0 ≤ stickers[i], limit[i] ≤ 109
- 1 ≤ R ≤ 1014
- 0 ≤ B ≤ 1014
- Use 64-bit integers
Examples
Example 1
Input:
4 10 7
8 5
3 10
10 0
6 2
Output:
2
Explanation: Customer 3 already has 10 stickers. Customer 1 needs 2 more (limit 5) — give them. Customer 2 needs 7 but only 5 bonus stickers remain. Customer 4 needs 4 but may receive only 2. Answer 2.
Example 2
Input:
3 100 50
60 45
90 5
95 10
Output:
2
Explanation: Customer 3 needs 5 (allowed) and customer 1 needs 40 (allowed): 45 ≤ 50. Customer 2 needs 10 but their limit is 5. Answer 2.
Note: The candidate remembered one free coffee per customer who reaches R stickers; the problem is written that way.
Approach
- Customer i needs
need = max(0, R − stickers[i])bonus stickers. Ifneed > limit[i], they can never get a coffee — drop them. - Every remaining customer is worth exactly 1, so serve the cheapest customers first: sort the needs and take them while the total fits in B.
- Exchange argument: swapping any chosen customer for a cheaper unchosen one never uses more stickers, so the greedy is optimal.
- R and B go up to 1014 — use
long long/long.
Complexity: Time: O(N log N) · Space: O(N)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; long long R, B;
cin >> n >> R >> B;
vector<long long> need;
for (int i = 0; i < n; i++) {
long long s, c; cin >> s >> c;
long long x = max(0LL, R - s); // bonus stickers still needed
if (x <= c) need.push_back(x); // only within this customer's bonus limit
}
sort(need.begin(), need.end()); // cheapest customers first
long long count = 0;
for (long long x : need) {
if (x > B) break;
B -= x; count++;
}
cout << count << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(System.in, 1 << 16));
int n = (int) readLong(in);
long R = readLong(in), B = readLong(in);
long[] need = new long[n];
int k = 0;
for (int i = 0; i < n; i++) {
long s = readLong(in), c = readLong(in);
long x = Math.max(0, R - s); // bonus stickers still needed
if (x <= c) need[k++] = x; // only within this customer's bonus limit
}
Arrays.sort(need, 0, k); // cheapest customers first
long count = 0;
for (int i = 0; i < k; i++) {
if (need[i] > B) break;
B -= need[i]; count++;
}
System.out.println(count);
}
static long readLong(DataInputStream in) throws IOException {
int b = in.read();
while (b != '-' && (b < '0' || b > '9')) b = in.read();
boolean neg = b == '-';
if (neg) b = in.read();
long r = 0;
while (b >= '0' && b <= '9') { r = r * 10 + (b - '0'); b = in.read(); }
return neg ? -r : r;
}
}
Show the Python solution
import sys
def main():
data = sys.stdin.buffer.read().split()
n, R, B = int(data[0]), int(data[1]), int(data[2])
need = []
for i in range(n):
s, c = int(data[3 + 2 * i]), int(data[4 + 2 * i])
x = max(0, R - s) # bonus stickers this customer still needs
if x <= c: # possible only within the customer's own bonus limit
need.append(x)
need.sort() # serve the cheapest customers first
count = 0
for x in need:
if x > B:
break
B -= x
count += 1
print(count)
main()
Question 12: Separated Domino Tiling
Difficulty: Hard · Topic: Profile DP, Matrix Exponentiation · Source: Infosys exam, Nov 2026, shared by candidates (reconstructed)
Problem
A board has 2 rows and n columns. You must cover every cell exactly once using two kinds of pieces:
- a square (1 × 1), and
- a domino (1 × 2), placed either horizontally or vertically.
No two dominoes may be adjacent: a cell of one domino must never share a side with a cell of a different domino (touching only at a corner is fine). Squares can be anywhere.
Count the number of different ways to cover the board. Print the answer modulo 109 + 7.
Input Format
- A single integer n, the number of columns.
Output Format
- Print the number of valid tilings modulo 109 + 7.
Constraints
- 1 ≤ n ≤ 1018
Examples
Example 1
Input:
2
Output:
5
Explanation: Four squares; one vertical domino in column 1 or in column 2 (2 ways); one horizontal domino on the top row or on the bottom row (2 ways). Two dominoes would always touch. Total 5.
Example 2
Input:
3
Output:
9
Explanation: For example the two vertical dominoes in columns 1 and 3 are allowed (column 2 has squares), but vertical dominoes in columns 1 and 2 touch and are not allowed.
Note: The candidate remembered a 2-row board, pieces of length 1 and 2, and “no domino adjacent to another”. The exact wording and limits were reconstructed.
Approach
- Describe one column by what covers its two cells: square, left half of a horizontal domino, right half, or a vertical domino. Because dominoes may not touch, only 6 column types are possible: (S,S), (S,L), (S,R), (L,S), (R,S), (V,V).
- A column type can follow another if every left half continues as a right half, and no domino cell sits next to a domino cell of a different domino. That gives a fixed 6 × 6 transition matrix T.
- Start from an imaginary empty column (S,S). The answer is the sum of
(Tⁿ)[start][j]over end types j that do not start a horizontal domino. - n goes up to 1018, so compute Tⁿ with fast matrix exponentiation (about 60 squarings of a 6 × 6 matrix).
Complexity: Time: O(6³ · log n) · Space: O(1)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<vector<ll>> Mat;
const ll MOD = 1000000007LL;
// Cell kinds: 0 = 1x1 tile, 1 = left half of horizontal domino, 2 = right half, 3 = vertical domino
const int S = 0, HL = 1, HR = 2, V = 3;
const int ST[6][2] = {{S, S}, {S, HL}, {S, HR}, {HL, S}, {HR, S}, {V, V}}; // one column (top, bottom)
bool ok(int a, int b) {
for (int r = 0; r < 2; r++) {
int p = ST[a][r], c = ST[b][r];
if (p == HL && c != HR) return false; // horizontal domino must continue
if (c == HR && p != HL) return false;
if ((p == V || p == HR) && (c == V || c == HL)) return false; // two dominoes side by side
}
return true;
}
Mat mul(const Mat &A, const Mat &B) {
int n = A.size();
Mat C(n, vector<ll>(n, 0));
for (int i = 0; i < n; i++)
for (int k = 0; k < n; k++) if (A[i][k])
for (int j = 0; j < n; j++) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD;
return C;
}
int main() {
ll n; cin >> n;
Mat T(6, vector<ll>(6, 0)), R(6, vector<ll>(6, 0));
for (int a = 0; a < 6; a++) for (int b = 0; b < 6; b++) T[a][b] = ok(a, b);
for (int i = 0; i < 6; i++) R[i][i] = 1;
for (ll e = n; e > 0; e >>= 1) { // R = T^n, n up to 10^18
if (e & 1) R = mul(R, T);
T = mul(T, T);
}
ll ans = 0;
for (int j = 0; j < 6; j++) // start from an empty column; the last column may not open a domino
if (ST[j][0] != HL && ST[j][1] != HL) ans = (ans + R[0][j]) % MOD;
cout << ans << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
static final long MOD = 1_000_000_007L;
// Cell kinds: 0 = 1x1 tile, 1 = left half of horizontal domino, 2 = right half, 3 = vertical domino
static final int S = 0, HL = 1, HR = 2, V = 3;
static final int[][] ST = {{S, S}, {S, HL}, {S, HR}, {HL, S}, {HR, S}, {V, V}}; // one column
static boolean ok(int a, int b) {
for (int r = 0; r < 2; r++) {
int p = ST[a][r], c = ST[b][r];
if (p == HL && c != HR) return false;
if (c == HR && p != HL) return false;
if ((p == V || p == HR) && (c == V || c == HL)) return false; // two dominoes side by side
}
return true;
}
static long[][] mul(long[][] A, long[][] B) {
int n = A.length;
long[][] C = new long[n][n];
for (int i = 0; i < n; i++)
for (int k = 0; k < n; k++) if (A[i][k] != 0)
for (int j = 0; j < n; j++) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD;
return C;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long n = Long.parseLong(br.readLine().trim());
long[][] T = new long[6][6], R = new long[6][6];
for (int a = 0; a < 6; a++) for (int b = 0; b < 6; b++) T[a][b] = ok(a, b) ? 1 : 0;
for (int i = 0; i < 6; i++) R[i][i] = 1;
for (long e = n; e > 0; e >>= 1) { // R = T^n, n up to 10^18
if ((e & 1) == 1) R = mul(R, T);
T = mul(T, T);
}
long ans = 0;
for (int j = 0; j < 6; j++)
if (ST[j][0] != HL && ST[j][1] != HL) ans = (ans + R[0][j]) % MOD;
System.out.println(ans);
}
}
Show the Python solution
import sys
MOD = 10**9 + 7
# A column of the 2 x n board is described by what fills its top and bottom cell:
# S = 1x1 tile, HL / HR = left / right half of a horizontal domino, V = vertical domino.
# Two domino cells of different dominoes may not touch, so inside one column at most
# one cell can be a horizontal-domino cell, or the column is one vertical domino.
S, HL, HR, V = 'S', 'HL', 'HR', 'V'
STATES = [(S, S), (S, HL), (S, HR), (HL, S), (HR, S), (V, V)]
def ok(prev, cur):
for p, c in zip(prev, cur):
if p == HL and c != HR: return False # a horizontal domino must continue
if c == HR and p != HL: return False
if p in (V, HR) and c in (V, HL): return False # two dominoes side by side
return True
T = [[1 if ok(a, b) else 0 for b in STATES] for a in STATES]
def mul(A, B):
n = len(A)
return [[sum(A[i][k] * B[k][j] for k in range(n)) % MOD for j in range(n)] for i in range(n)]
def main():
n = int(sys.stdin.read().split()[0])
size = len(STATES)
R = [[int(i == j) for j in range(size)] for i in range(size)]
P = T
e = n
while e: # R = T^n by fast exponentiation (n can be 10^18)
if e & 1: R = mul(R, P)
P = mul(P, P)
e >>= 1
start = 0 # an imaginary empty column (S, S) before the board
ans = sum(R[start][j] for j, st in enumerate(STATES) if HL not in st) % MOD
print(ans)
main()
Question 13: Nurse Duty Roster
Difficulty: Complex · Topic: DP, Matrix Exponentiation · Source: Infosys exam, Nov 2026, shared by candidates (reconstructed)
Problem
A hospital plans the duty roster of a nurse for N days. On every day the nurse is on exactly one of: Day shift (D), Night shift (N) or Leave (L).
A roster is valid when all three rules hold:
- The nurse never works a Day shift on the day right after a Night shift (no “N D”).
- The nurse never works more than K Night shifts in a row.
- The nurse never takes more than M Leave days in a row.
Count the number of valid rosters for N days. Print the answer modulo 109 + 7.
Input Format
- A single line with three integers N, K and M.
Output Format
- Print the number of valid rosters modulo 109 + 7.
Constraints
- 1 ≤ N ≤ 1018
- 1 ≤ K, M ≤ 10
Examples
Example 1
Input:
2 1 1
Output:
6
Explanation: All 9 pairs minus the invalid ones: ND (Day after Night), NN (2 Nights > K), LL (2 Leaves > M). The valid rosters are DD, DN, DL, NL, LD, LN — 6.
Example 2
Input:
3 2 1
Output:
15
Explanation: Here two Nights in a row are allowed (K = 2) but not two Leave days (M = 1); 15 of the 27 rosters satisfy all rules.
Note: The candidate remembered: total days, a limit on consecutive night shifts, “no Day shift after a Night shift”, one more forgotten input, and constraints of about 10^14–10^20. The forgotten input is taken as the limit M on consecutive leave days.
Approach
- Only the end of the roster matters: whether the last day was a Day shift, or how many Nights / Leaves the roster currently ends with. That gives
1 + K + Mstates. - Transitions: after Day anything is allowed; after j Nights you may take another Night only if j < K, or Leave (never Day); after j Leaves you may take Day, Night, or another Leave only if j < M.
- The number of rosters of length N is the sum of row “start” of
Tᴺ(start behaves like a Day: no restriction for the first day). - N reaches 1018, so use matrix exponentiation: (1 + K + M)³ · log N ≈ 21³ · 60 operations.
Complexity: Time: O((K + M)³ · log N) · Space: O((K + M)²)
Solutions in C++, Java and Python
Show the C++ solution
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<vector<ll>> Mat;
const ll MOD = 1000000007LL;
Mat mul(const Mat &A, const Mat &B) {
int n = A.size();
Mat C(n, vector<ll>(n, 0));
for (int i = 0; i < n; i++)
for (int k = 0; k < n; k++) if (A[i][k])
for (int j = 0; j < n; j++) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD;
return C;
}
int main() {
ll N; int K, M;
cin >> N >> K >> M;
// states: 0 = last shift was Day (also the start); 1..K = j nights in a row; K+1..K+M = j leave days in a row
int size = 1 + K + M;
auto night = [&](int j) { return j; };
auto leave = [&](int j) { return K + j; };
Mat T(size, vector<ll>(size, 0)), R(size, vector<ll>(size, 0));
T[0][0] = T[0][night(1)] = T[0][leave(1)] = 1; // after Day: anything
for (int j = 1; j <= K; j++) { // after Night: never Day
if (j < K) T[night(j)][night(j + 1)] = 1;
T[night(j)][leave(1)] = 1;
}
for (int j = 1; j <= M; j++) { // after Leave
T[leave(j)][0] = 1;
T[leave(j)][night(1)] = 1;
if (j < M) T[leave(j)][leave(j + 1)] = 1;
}
for (int i = 0; i < size; i++) R[i][i] = 1;
for (ll e = N; e > 0; e >>= 1) { // R = T^N, N up to 10^18
if (e & 1) R = mul(R, T);
T = mul(T, T);
}
ll ans = 0;
for (int j = 0; j < size; j++) ans = (ans + R[0][j]) % MOD;
cout << ans << "\n";
return 0;
}
Show the Java solution
import java.util.*;
import java.io.*;
public class Main {
static final long MOD = 1_000_000_007L;
static long[][] mul(long[][] A, long[][] B) {
int n = A.length;
long[][] C = new long[n][n];
for (int i = 0; i < n; i++)
for (int k = 0; k < n; k++) if (A[i][k] != 0)
for (int j = 0; j < n; j++) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD;
return C;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long N = Long.parseLong(st.nextToken());
int K = Integer.parseInt(st.nextToken()), M = Integer.parseInt(st.nextToken());
// states: 0 = last shift was Day (also the start); 1..K = j nights in a row; K+1..K+M = j leave days in a row
int size = 1 + K + M;
long[][] T = new long[size][size], R = new long[size][size];
T[0][0] = 1; T[0][1] = 1; T[0][K + 1] = 1; // after Day: anything
for (int j = 1; j <= K; j++) { // after Night: never Day
if (j < K) T[j][j + 1] = 1;
T[j][K + 1] = 1;
}
for (int j = 1; j <= M; j++) { // after Leave
T[K + j][0] = 1;
T[K + j][1] = 1;
if (j < M) T[K + j][K + j + 1] = 1;
}
for (int i = 0; i < size; i++) R[i][i] = 1;
for (long e = N; e > 0; e >>= 1) { // R = T^N, N up to 10^18
if ((e & 1) == 1) R = mul(R, T);
T = mul(T, T);
}
long ans = 0;
for (int j = 0; j < size; j++) ans = (ans + R[0][j]) % MOD;
System.out.println(ans);
}
}
Show the Python solution
import sys
MOD = 10**9 + 7
def mul(A, B):
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
Ai, Ci = A[i], C[i]
for k in range(n):
a = Ai[k]
if a:
Bk = B[k]
for j in range(n):
Ci[j] += a * Bk[j]
for j in range(n):
Ci[j] %= MOD
return C
def main():
N, K, M = map(int, sys.stdin.read().split()[:3])
# states: 0 = last shift was Day (also the start),
# 1..K = the last j shifts were Nights, K+1..K+M = the last j days were Leave
size = 1 + K + M
night = lambda j: j # j consecutive nights
leave = lambda j: K + j # j consecutive leave days
T = [[0] * size for _ in range(size)]
T[0][0] = T[0][night(1)] = T[0][leave(1)] = 1 # after Day: anything
for j in range(1, K + 1): # after Night: no Day
if j < K: T[night(j)][night(j + 1)] = 1
T[night(j)][leave(1)] = 1
for j in range(1, M + 1): # after Leave
T[leave(j)][0] = 1
T[leave(j)][night(1)] = 1
if j < M: T[leave(j)][leave(j + 1)] = 1
R = [[int(i == j) for j in range(size)] for i in range(size)]
e = N
while e: # R = T^N, N up to 10^18
if e & 1: R = mul(R, T)
T = mul(T, T)
e >>= 1
print(sum(R[0]) % MOD)
main()
Preparing for the Infosys Coding Round
Look at the topics in the table above: greedy with sorting, dynamic programming, and matrix exponentiation for very large N. If you can solve the easy and medium questions here without help, spend the rest of your time on the hard ones.
Applying to Infosys right now? Read our post on the Infosys Off Campus Drive 2026 for SP and DSE roles for eligibility, the selection process and the official apply link.
For a structured plan, I have also written the Infosys Coding Test Master Guide. It is a paid guide by the author, available on Topmate.
FAQs: Infosys Coding Questions
Are these the exact questions from the Infosys exam?
No. Candidates recalled them from memory, so the wording and numbers may differ from the real paper, and some questions were reconstructed. Use them to practise the patterns, not to memorise answers.
Which programming language should I use?
Use the language you are fastest in. Every question here has a solution in C++, Java and Python. For large inputs, use fast input methods like the ones in the Java solutions.
Are the solutions tested?
Yes. Each solution runs correctly on both examples in this post and was checked against a brute-force answer on random tests.
Will the same questions come again?
Nobody can promise that. Learn the approach behind each question, so you can solve a new question on the same topic.
Do I need to know matrix exponentiation?
Two of the 13 questions (Separated Domino Tiling and Nurse Duty Roster) need it, because N can be as large as 1018. Learn it after you are comfortable with basic DP.
