Josephus

‘N’ people are standing in a circle numbered from ‘1’ to ‘N’ in clockwise order. First, the person numbered 1 will proceed in a clockwise direction and will skip K-1 persons including itself and will kill a Kth person. Now (K+1)th person from 1 will start and will kill the Kth person from itself.

You have to find the position of the last person surviving with respect to initial numbering.

Note:
A person can also kill himself.
Input Format
The first line of input contains an integer ‘T’ denoting the number of test cases.

The first and only line of each test case contains two integers ‘N’ and ‘K’. Where ‘N’ is the total no of persons standing around circle and ‘K’  number indicates kth person is killed. 
Output Format
For each test case, return a single integer denoting the position of the last person surviving.  
Note:
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.

Constraints

1 <= ’T’ <= 50
1 <= ’N’,’K’ <= 10^4

Time Limit: 1 sec
AnswerBot
1y

This question is about finding the position of the last person surviving in a circle of N people, where each person kills the Kth person in a clockwise direction.

  • Implement a function that takes the nu...read more

CodingNinjas
author
2y
Brute Force

Approach:- The key id is to store all positions of a person in vector and remove all kth position from starting point in vector. After removing an element from the vector starting point is ...read more

CodingNinjas
author
2y
Approach2

The key idea is find the answer for ‘N’ persons around the circle first find the answer for 'N-1' persons. First kill the Kth person from 1st position then recursively call on 'N-1'. It will ...read more

Add answer anonymously...
Texas Instruments Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter