Solve the Josephus problem. There are n people standing in a circle, numbered 1 to n. Starting from person 1, you count k people around the circle and eliminate the kth person. Counting then resumes from the next person, and the process repeats until only one person remains. Return the 1-based position of the survivor.

Examples:

Input: n = 7, k = 3 Output: 4 Explanation: Order of elimination is 3, 6, 2, 7, 5, 1, leaving 4 Input: n = 5, k = 2 Output: 3 Explanation: Order of elimination is 2, 4, 1, 5, leaving 3 Input: n = 1, k = 1 Output: 1 Explanation: With one person, that person survives Input: n = 6, k = 2 Output: 5 Explanation: The survivor is at position 5 Input: n = 10, k = 2 Output: 5 Explanation: The survivor is at position 5
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay November 2026 (Nov 1–15)Sponsored by FLXBL

Contest runs November 1 - 15. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In