Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Save the Prisoner! Problem Solution

Yashwant Parihar, April 15, 2023April 16, 2023

In this post, we will solve HackerRank Save the Prisoner! Problem.

A jail has a number of prisoners and a number of treats to pass out to them. Their jailer decides the fairest way to divide the treats is to seat the prisoners around a circular table in sequentially numbered chairs. A chair number will be drawn from a hat. Beginning with the prisoner in that chair, one candy will be handed to each prisoner sequentially around the table until all have been distributed.

The jailer is playing a little joke, though. The last piece of candy looks like all the others, but it tastes awful. Determine the chair number occupied by the prisoner who will receive that candy.

Example

n = 4

m = 6

8 = 2

There are 4 prisoners, 6 pieces of candy and distribution starts at chair 2. The prisoners arrange themselves in seats numbered 1 to 4. Prisoners receive candy at positions 2, 3, 4, 1, 2, 3. The prisoner to be warned sits in chair number 3.

Function Description

Complete the saveThePrisoner function in the editor below. It should return an integer representing the chair number of the prisoner to warn.

saveThePrisoner has the following parameter(s):

  • int n: the number of prisoners
  • int m: the number of sweets
  • int s: the chair number to begin passing out sweets from

Returns

  • int: the chair number of the prisoner to warn

Input Format

The first line contains an integer, t, the number of test cases.
The next t lines each contain 3 space-separated integers:

  • n : the number of prisoners
  • m : the number of sweets
  • s : the chair number to start passing out treats at

Sample Input 0

2
5 2 1
5 2 2

Sample Output 0

2
3

Explanation 0

In the first query, there are n = 5 prisoners and m = 2 sweets. Distribution starts at seat number 8 = 1. Prisoners in seats numbered 1 and 2 get sweets.

In the second query, distribution starts at seat 2 so prisoners in seats 2 and 3 get sweets. Warn prisoner 2. Warn prisoner 3.

Sample Input 1

2
7 19 2
3 7 3

Sample Output 1

6
3

Explanation 1

In the first test case, there are n = 7 prisoners, m = 19 sweets and they are passed out starting at chair 8 = 2. The candies go all around twice and there are 5 more candies passed to each prisoner from seat 2 to seat 6. In the second test case, there are n = 3 prisoners, m = 7 candies and they are passed out starting at seat & = 3. They go around twice, and there is one more to pass out to the prisoner at seat 3.

HackerRank Save the Prisoner! Problem Solution
HackerRank Save the Prisoner! Problem Solution

Save the Prisoner! C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    int T, N, M, S, result;
    scanf("%d", &T);
    while(T > 0)
        {
        scanf("%d %d %d", &N, &M, &S);
        if(N == 1)
            {
            result = 1;
        }
        else
            {
                result = S + M - 1;
                if(result > N)
                    {
                    result = result % N;
                    if(result == 0)
                        {
                        if(S == 1)
                            {
                            result = N;
                        }
                        else
                            {
                            result = S + (M % N) - 1;
                        }
                        
                    }
            }
        }
        
        printf("%d\n", result);
        T--;
    }
    return 0;
}

Save the Prisoner! C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int T;
    cin >> T;
    int N, M, S;
    while (T--) {
        cin >> N >> M >> S;
        cout << ((S + M - 2) % N) + 1 << endl;
    }
    return 0;
}

Save the Prisoner! C Sharp Solution

#include <iostream>

using namespace std;

int T;
long long N,M,S;
long long ans;

int main()
{
    cin >> T;

    while(T--)
    {
        cin >> N >> M >> S;
        ans = (S-1 + M - 1) % N + 1;

        cout << ans << '\n';
    }

    return 0;
}

Save the Prisoner! Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'saveThePrisoner' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER n
     *  2. INTEGER m
     *  3. INTEGER s
     */

    public static int saveThePrisoner(int n, int m, int s) {
        return (m -1 +s -1) % n +1;

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int t = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, t).forEach(tItr -> {
            try {
                String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

                int n = Integer.parseInt(firstMultipleInput[0]);

                int m = Integer.parseInt(firstMultipleInput[1]);

                int s = Integer.parseInt(firstMultipleInput[2]);

                int result = Result.saveThePrisoner(n, m, s);

                bufferedWriter.write(String.valueOf(result));
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Save the Prisoner! JavaScript Solution

function processData(input) {
    //Enter your code here
    var inArr=input.split("\n");
    for(i=1;i<inArr.length;i++){
        var line=inArr[i].split(" ");
        var res=(parseInt(line[2])+parseInt(line[1])-1)%line[0];
        if(res==0)res=line[0];
        console.log(res);
        
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Save the Prisoner! Python Solution

x = int(input())
for i in range(x):
    l = input().split()
    n = int(l[0])
    m = int(l[1])
    s = int(l[2])
    if (m+s)<n:
        print (m+s-1)
    else:
        if (((m+s)%n)-1) == 0:
            print (n)
        else:
            print (((m+s)%n)-1)

Other Solutions

  • HackerRank Circular Array Rotation Solution
  • HackerRank Sequence Equation Problem Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes