LeetCode 1033: Moving Stones Until Consecutive Solution
Master LeetCode problem 1033 (Moving Stones Until Consecutive), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1033. Moving Stones Until Consecutive
Problem Explanation
Explanation
To solve this problem, we need to find the minimum and maximum number of moves required to move the stones until they are in consecutive positions.
- Calculate the minimum moves:
- The minimum number of moves is determined by moving the stone closest to the middle stone to the middle position adjacent to it.
- Calculate the distance between the stones and consider the edge cases where the stones are already consecutive.
- Calculate the maximum moves:
- The maximum number of moves is determined by moving the stones to the two gaps between them.
- Calculate the distance between the stones and consider the edge cases where the stones are already consecutive.
The time complexity of this algorithm is O(1) as we are performing constant operations, and the space complexity is also O(1) as we are not using any extra space.
Solution Code
class Solution {
public int[] numMovesStones(int a, int b, int c) {
int[] stones = {a, b, c};
Arrays.sort(stones);
if (stones[2] - stones[0] == 2) { // Already consecutive
return new int[]{0, 0};
} else {
int minMoves = (stones[1] - stones[0] <= 2 || stones[2] - stones[1] <= 2) ? 1 : 2;
int maxMoves = stones[2] - stones[0] - 2;
return new int[]{minMoves, maxMoves};
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1033 (Moving Stones Until Consecutive)?
This page provides optimized solutions for LeetCode problem 1033 (Moving Stones Until Consecutive) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1033 (Moving Stones Until Consecutive)?
The time complexity for LeetCode 1033 (Moving Stones Until Consecutive) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1033 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1033 in Java, C++, or Python.