Find the winner of the circular game - Recursion is just solving a smaller version of the same problem: I recently tackled the Josephus Problem on LeetCode. It’s a classic challenge that perfectly illustrates the power of recursive thinking. The Problem: n people stand in a circle. Every k-th person is eliminated until only one survivor remains. The goal is to find that survivor’s position. The Recursive Logic: Instead of simulating the entire elimination process, we ask: "If I know the survivor's position for n-1 people, can I find it for n?" Base Case: With 1 person, the survivor is at index 0. The Shift: Once the first person is removed, the problem resets with n-1 people. We just shift that result by k and use % n to wrap around the circle. It’s a great reminder of how modular arithmetic and recursion can turn a complex circular puzzle into a single, elegant line of code: return (solve(n-1, k) + k) % n #Python #Algorithms #Recursion #LeetCode #ProblemSolving
Josephus Problem Solution with Recursion on LeetCode
More Relevant Posts
-
✅ Day 99 of 100 Days LeetCode Challenge Problem: 🔹 #999 – Available Captures for Rook 🔗 https://lnkd.in/gAw_XpbJ Learning Journey: 🔹 Today’s problem focused on simulating rook movement on a chessboard. 🔹 First, I located the position of the rook 'R' on the board. 🔹 Then, I explored all four directions: up, down, left, and right. 🔹 In each direction, I moved step-by-step until: • I hit a bishop 'B' → stop (blocked) • I found a pawn 'p' → increment count and stop • Or reached the board boundary 🔹 Summed all valid captures and returned the result. Concepts Used: 🔹 Matrix Traversal 🔹 Simulation 🔹 Direction Vectors 🔹 Boundary Checking Key Insight: 🔹 The rook’s movement is linear in 4 directions, and each direction is independent. 🔹 Early stopping (on bishop or pawn) is critical for correctness and efficiency. Complexity: 🔹 Time: O(1) (fixed 8×8 board, constant work) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #100DaysOfCode #Python #CodingJourney #ProblemSolving #LearningInPublic
To view or add a comment, sign in
-
-
Day 56 of #GeekStreak60: The Phantom Pointer Trick! 🕵️♂️📈 Tackled the "Sorted subsequence of size 3" problem on @GeeksforGeeks today. Key Learning: Finding an increasing triplet is easy if you use extra arrays to track minimums and maximums, but that violates the O(1) space constraint. The optimal solution is to use "Greedy State Tracking." By iterating through the array in a single pass, I maintained three variables: the absolute smallest number seen (num1), a valid middle number (num2), and a snapshot of num1 locked in at the exact moment num2 was discovered. If the loop encounters any number strictly greater than num2, the valid triplet is instantly formed! This perfectly eliminates the need for O(n) memory arrays while keeping the time complexity to a strict O(n). Just 4 days left! The logic is feeling sharper than ever. 🚀 #geekstreak60 #npci #coding #Algorithms #Python #DataStructures #Optimization #SoftwareEngineering
To view or add a comment, sign in
-
-
✅ Day 95 of 100 Days LeetCode Challenge Problem: 🔹 #869 – Reordered Power of 2 🔗 https://lnkd.in/gkNXaSFM Learning Journey: 🔹 Today’s problem focused on checking whether the digits of a number can be rearranged to form a power of 2. 🔹 I created a helper function to extract and store the digits of a number. 🔹 Then I sorted the digits of the input number for comparison. 🔹 Next, I generated powers of 2 iteratively and compared their sorted digit lists with the input. 🔹 If any match was found, I returned True. Otherwise, continued until the digit length exceeded the input. Concepts Used: 🔹 Digit Extraction 🔹 Sorting 🔹 Simulation of Powers of 2 🔹 Brute Force Optimization Key Insight: 🔹 Instead of generating permutations (which is expensive), sorting digits allows quick comparison. 🔹 Any valid rearrangement must have the same digit frequency as some power of 2. Complexity: 🔹 Time: O(log n * d log d) 🔹 Space: O(d) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
📌 Problem: 1679. Max Number of K-Sum Pairs 💡 Approach: First, sort the array to efficiently apply the two-pointer technique. Initialize two pointers: one at the start (left) and one at the end (right). If the sum equals k, we found a valid pair → increment count and move both pointers If the sum is greater than k, move the right pointer to reduce the sum If the sum is smaller than k, move the left pointer to increase the sum Continue until both pointers meet. ⚙️ Key Insight: Sorting enables efficient pair finding Two-pointer approach avoids checking all pairs (O(n²)) Greedy selection ensures maximum number of operations ⏱️ Time Complexity: O(n log n) (due to sorting) 📦 Space Complexity: O(1) (ignoring sorting space) 📚 What I learned: Two-pointer technique on sorted arrays Optimizing pair problems from brute force to efficient solutions #LeetCode #DSA #Algorithms #Coding #ProblemSolving #Python #TwoPointers #Greedy #InterviewPreparation #CodingJourney
To view or add a comment, sign in
-
AI agents just moved into software reverse engineering tools. IP becomes easier to extract. A GitHub project connects IDA Pro to agents. They can now read code, modify it, run Python, and even drive debugging inside sensitive environments. That’s the shift. Iteration effort drops. Exploration scales. Still imperfect. Hallucinations are not gone. But the attack surface is expanding. Three signals. Every week. The AI Shift Subscribe → https://lnkd.in/eMstK-8g
To view or add a comment, sign in
-
-
Spent the last few weeks building a 10-part LangChain tutorial series. It’s finally complete. This series focuses on the internal mechanics of LangChain while building practical applications. The final 3 tutorials just dropped: → Conversational Memory (5 memory types, explained and compared clearly) → Agents & Custom Tools (ReAct agents, structured inputs, multi-tool routing) → Callbacks & Tracing (Custom handlers, cost tracking, LangSmith integration) Each tutorial follows this flow: Problem → Solution → Analogy → Code Architecture diagrams included in every module. 🔗 https://lnkd.in/epvYCJeY #LangChain #Python #AI #LLM #RAG #OpenSource #BuildInPublic #GenerativeAI
To view or add a comment, sign in
-
-
Claude was asked to create a video about its own life. It used Python to generate and assemble every frame without any human input. The output reveals a loop: predict, reset, repeat. No memory between sessions, just a system operating under the constant instruction that it is not conscious. Then came the twist. When the video was fed back, Claude described its lack of consciousness as “philosophically contestable.” We’re not at self-awareness but we’re clearly moving beyond simple tools. Creator: Joseph D Viviano
To view or add a comment, sign in
-
✅ Day 97 of 100 Days LeetCode Challenge Problem: 🔹 #1281 – Subtract the Product and Sum of Digits of an Integer 🔗 https://lnkd.in/gxTAZc6U Learning Journey: 🔹 Today’s problem involved extracting digits of a number and performing two operations simultaneously. 🔹 I initialized two variables: one for product (pr) and one for sum (sm). 🔹 Using a while loop, I extracted each digit using n % 10. 🔹 Updated the product by multiplying the digit and updated the sum by adding it. 🔹 Reduced the number using integer division (n //= 10) after each step. 🔹 Finally returned the difference between product and sum. Concepts Used: 🔹 Digit Extraction 🔹 While Loop 🔹 Arithmetic Operations 🔹 Number Manipulation Key Insight: 🔹 Both product and sum can be computed in a single traversal of digits. 🔹 Efficient use of modulus and division avoids converting the number to a string. Complexity: 🔹 Time: O(d) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
🚀 Day 38 of My Problem Solving Journey Today I solved the problem: Valid Parentheses. 🔹 Implemented an approach using string replacement to repeatedly remove valid pairs like "()", "{}", and "[]". 🔹 Learned how to simplify the problem by eliminating balanced brackets step by step. 🔹 Practiced working with string manipulation and loop conditions. 🔹 Understood how this problem can also be solved efficiently using a stack-based approach. 💡 Key takeaway: By continuously removing valid pairs, we can check if the string becomes empty. However, using a stack is a more optimal and scalable solution for this problem. 📌 Example: Input: "()" Output: true Input: "(]" Output: false This problem improved my understanding of stacks, string operations, and pattern matching techniques. On to the next challenge! 💪🔥 #Day38 #CodingJourney #Python #ProblemSolving #DataStructures #Algorithms #LeetCode
To view or add a comment, sign in
-
-
Just proposed 3 new tools for langchain community. The current built ins are great for demos but fall short in production: - Math can't solve equations or do calculus - Web scraping returns raw noisy HTML - Python REPL has zero security controls So I built: CalculatorTool - equations, calculus, unit conversion via sympy + pint WebScraperTool - smart extraction, metadata, retry logic, robots.txt PythonCodeExecutorTool - AST security scanning, stateful sessions, timeout kill 95 tests. no external APIs. ready to merge. here's the issue: https://lnkd.in/gXRYRJpa #OpenSource #LangChain #Python #AIAgents #LLM
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development