HackerRank Save the Prisoner Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Save the Prisoner Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Save the Prisoner Solution
HackerRank Save the Prisoner Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Save the Prisoner


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.


n = 4
m = 6
s = 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


  • 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


  • 1 <= t <= 100
  • 1 <= n <= 109
  • 1 <= m <= 109
  • 1 <= s <= n

Sample Input 0

5 2 1
5 2 2

Sample Output 0


Explanation 0

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

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

Sample Input 1

7 19 2
3 7 3

Sample Output 1


Explanation 1

In the first test case,

there are n = 7 prisoners, m = 19 sweets and they are passed out starting at chair s = 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 s = 3. They go around twice, and there is one more to pass out to the prisoner at seat 3.

HackerRank Save the Prisoner Solution

Save the Prisoner Solution in C

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

int main() {
    int t, n, m, s;
    scanf("%d", &t);
    while (t--) scanf("%d%d%d", &n, &m, &s), printf("%d\n", (m+s-2)%n+1);
    return 0;

Save the Prisoner Solution in Cpp

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

int main() {
    int t; cin >> t;
    while(t--) {
        int n,m,s; cin >> n >> m >> s;
        --s; --m;
        s += m;
        s %= n;
        cout << s << endl;
    return 0;

Save the Prisoner Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int rounds = input.nextInt();
        for(int i = 0; i < rounds; i++)
            int num = input.nextInt();
            int lop = input.nextInt();
            int s = input.nextInt() - 1;
            while(lop != 0)
                if(s > num)
                    s = 1;

Save the Prisoner Solution in Python

for i in range(x):
    [N,M,S]=[int(j) for j in raw_input().split()]
    val= (N+M+S-1)%N
    if val==0:
        print N
        print val

Save the Prisoner Solution using JavaScript


var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");

function readLine() {
    return input_stdin_array[input_currentline++];

/////////////// ignore above this line ////////////////////

function main() {
    var T = readLine();
    while(T--) {
        var P = readLine().split(' ');
        var N = +P[0]-1;
        var M = +P[1]-1;
        var S = +P[2]-1;
        // 0 1 2 3 4
        // 1 2
        if (S+M<N) {
        } else {
            console.log((  (S+M)%(N+1) ) + 1 );

Save the Prisoner Solution in Scala

object Solution {

  def main(args: Array[String]) {
    val input = readInput
    for (c <- input) {
      println(poisoned(c._1, c._2, c._3))

  def poisoned(n: Int, toDist: Int, s: Int): Int = {
    var m = toDist
    while (m > n)
      m -= n
    if (s + m <= n + 1) s + m - 1
    else m - (n - s + 1)

  def readInput: (List[(Int, Int, Int)]) = {
    val sc = new java.util.Scanner(System.in)
    val t = sc.nextInt()
    var list: List[(Int, Int, Int)] = Nil

    for (i <- 0 until t) {
      list = list ++ List((sc.nextInt(), sc.nextInt(), sc.nextInt()))


Save the Prisoner Solution in Pascal

var N,M,S,i,T:longint;
R:array[-1..104] of longint;
for i:=1 to T do
r[i]:=(m+s-1) mod n;
if r[i]=0 then r[i]:=n;
for i:=1 to T do writeln(R[i]);

Disclaimer: This problem (Save the Prisoner) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment