-
Notifications
You must be signed in to change notification settings - Fork 20.5k
Shortest coprime segment using sliding window technique #6296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
DenizAltunkapan
merged 6 commits into
TheAlgorithms:master
from
DomTr:sliding-window-gcd
Jun 18, 2025
+200
−0
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
71dd8f7
Shortest coprime segment using sliding window technique
DomTr 64cd545
mvn checkstyle passes
DomTr c78dd46
gcd function reformatted
DomTr 151fb27
fixed typo in ShortestCoprimeSegment
DomTr 911061d
1. shortestCoprimeSegment now returns not the length, but the shortes…
DomTr 8bcd7db
clang formatted ShortestCoprimeSegmentTest.java code
DomTr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
117 changes: 117 additions & 0 deletions
117
src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
package com.thealgorithms.slidingwindow; | ||
|
||
import java.util.LinkedList; | ||
|
||
/** | ||
* The Sliding Window technique together with 2-stack technique is used to find the minimal size of coprime segment in an array. | ||
* Segment a[i],...,a[i+l] is coprime if gcd(a[i], a[i+1], ..., a[i+l]) = 1 | ||
* <p> | ||
* Run-time complexity: O(n log n) | ||
* What is special about this 2-stack technique is that it enables us to remove element a[i] and find gcd(a[i+1],...,a[i+l]) in amortized O(1) time. | ||
* For 'remove' worst-case would be O(n) operation, but this happens rarely. | ||
* Main observation is that each element gets processed a constant amount of times, hence complexity will be: | ||
* O(n log n), where log n comes from complexity of gcd. | ||
* <p> | ||
* The 2-stack technique enables us to 'remove' an element fast if it is known how to 'add' an element fast to the set. | ||
* In our case 'adding' is calculating d' = gcd(a[i],...,a[i+l+1]), when d = gcd(a[i],...a[i]) with d' = gcd(d, a[i+l+1]). | ||
* and removing is find gcd(a[i+1],...,a[i+l]). We don't calculate it explicitly, but it is pushed in the stack which we can pop in O(1). | ||
* <p> | ||
* One can change methods 'legalSegment' and function 'f' in DoubleStack to adapt this code to other Silding-window type problems. | ||
* I recommend this article for more explanations: https://codeforces.com/edu/course/2/lesson/9/2 or https://usaco.guide/gold/sliding-window?lang=cpp#method-2---two-stacks | ||
* <p> | ||
* Another method to solve this problem is through segment trees. Then query operation would have O(log n), not O(1) time, but runtime complexity would still be O(n log n) | ||
* | ||
* @author DomTr (https://github.com/DomTr) | ||
*/ | ||
public class ShortestCoprimeSegment { | ||
// Prevent instantiation | ||
private ShortestCoprimeSegment() { | ||
} | ||
|
||
/** | ||
* @param arr is the input array | ||
* @param n is the array size | ||
* @return the length of the smallest segment in the array which has gcd equal to 1. If no such segment exists, returns -1 | ||
*/ | ||
public static int shortestCoprimeSegment(int n, long[] arr) { | ||
DenizAltunkapan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
DenizAltunkapan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
DoubleStack front = new DoubleStack(); | ||
DoubleStack back = new DoubleStack(); | ||
int l = 0, best = n + 1; | ||
for (int i = 0; i < n; i++) { | ||
back.push(arr[i]); | ||
while (legalSegment(front, back)) { | ||
remove(front, back); | ||
best = Math.min(best, i - l + 1); | ||
l++; | ||
} | ||
} | ||
if (best > n) best = -1; | ||
return best; | ||
} | ||
|
||
private static boolean legalSegment(DoubleStack front, DoubleStack back) { | ||
return gcd(front.top(), back.top()) == 1; | ||
} | ||
|
||
private static long gcd(long a, long b) { | ||
if (a < b) return gcd(b, a); | ||
else if (b == 0) return a; | ||
else return gcd(a % b, b); | ||
} | ||
|
||
/** | ||
* This solves the problem of removing elements quickly. | ||
* Even though the worst case of 'remove' method is O(n), it is a very pessimistic view. | ||
* We will need to empty out 'back', only when 'from' is empty. | ||
* Consider element x when it is added to stack 'back'. | ||
* After some time 'front' becomes empty and x goes to 'front'. Notice that in the for-loop we proceed further and x will never come back to any stacks 'back' or 'front'. | ||
* In other words, every element gets processed by a constant number of operations. | ||
* So 'remove' amortized runtime is actually O(n). | ||
*/ | ||
private static void remove(DoubleStack front, DoubleStack back) { | ||
if (front.isEmpty()) { | ||
while (!back.isEmpty()) { | ||
front.push(back.pop()); | ||
} | ||
} | ||
front.pop(); | ||
} | ||
|
||
/** | ||
* DoubleStack serves as a collection of two stacks. One is a normal stack called 'stack', the other 'values' stores gcd-s up until some index. | ||
*/ | ||
private static class DoubleStack { | ||
LinkedList<Long> stack, values; | ||
|
||
public DoubleStack() { | ||
values = new LinkedList<>(); | ||
stack = new LinkedList<>(); | ||
values.add((long) 0); // Initialise with 0 which is neutral element in terms of gcd, i.e. gcd(a,0) = a | ||
DenizAltunkapan marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
long f(long a, long b) { // Can be replaced with other function | ||
return gcd(a, b); | ||
} | ||
|
||
public void push(long x) { | ||
stack.addLast(x); | ||
values.addLast(f(values.getLast(), x)); | ||
} | ||
|
||
public long top() { | ||
return values.getLast(); | ||
} | ||
|
||
public long pop() { | ||
long res = stack.getLast(); | ||
stack.removeLast(); | ||
values.removeLast(); | ||
return res; | ||
} | ||
|
||
public boolean isEmpty() { | ||
return stack.isEmpty(); | ||
} | ||
} | ||
|
||
} |
39 changes: 39 additions & 0 deletions
39
src/test/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegmentTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package com.thealgorithms.slidingwindow; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
/** | ||
* Unit tests for ShortestCoprimeSegment algorithm | ||
* | ||
* @author DomTr (https://github.com/DomTr) | ||
*/ | ||
public class ShortestCoprimeSegmentTest { | ||
@Test | ||
public void testShortestCoprimeSegment() { | ||
assertEquals(3, ShortestCoprimeSegment.shortestCoprimeSegment(5, new long[]{4, 6, 9, 3, 6})); | ||
assertEquals(2, ShortestCoprimeSegment.shortestCoprimeSegment(5, new long[]{4, 5, 9, 3, 6})); | ||
assertEquals(2, ShortestCoprimeSegment.shortestCoprimeSegment(2, new long[]{3, 2})); | ||
assertEquals(2, ShortestCoprimeSegment.shortestCoprimeSegment(5, new long[]{3, 9, 9, 9, 10})); | ||
assertEquals(4, ShortestCoprimeSegment.shortestCoprimeSegment(4, new long[]{3 * 7, 7 * 5, 5 * 7 * 3, 3 * 5})); | ||
assertEquals(4, ShortestCoprimeSegment.shortestCoprimeSegment(4, new long[]{3 * 11, 11 * 7, 11 * 7 * 3, 3 * 7})); | ||
assertEquals(5, ShortestCoprimeSegment.shortestCoprimeSegment(5, new long[]{3 * 11, 11 * 7, 11 * 7 * 3, 11 * 7 * 3 * 5, 5 * 7})); | ||
assertEquals(6, ShortestCoprimeSegment.shortestCoprimeSegment(6, new long[]{3 * 11, 11 * 7, 11 * 7 * 3, 11 * 7 * 3 * 5, 11 * 7 * 3 * 5 * 13, 7 * 13})); | ||
assertEquals(6, ShortestCoprimeSegment.shortestCoprimeSegment(7, new long[]{3 * 11, 11 * 7, 11 * 7 * 3, 11 * 7 * 3 * 5, 11 * 7 * 3 * 5 * 13, 7 * 13, 11 * 7 * 3 * 5 * 13})); | ||
assertEquals(10, ShortestCoprimeSegment.shortestCoprimeSegment(10, new long[]{3 * 11, 7 * 11, 3 * 7 * 11, 3 * 5 * 7 * 11, 3 * 5 * 7 * 11 * 13, 2 * 3 * 5 * 7 * 11 * 13, 2 * 3 * 5 * 7 * 11 * 13 * 17, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23, 7 * 13})); | ||
// Segment can consist of one element | ||
assertEquals(1, ShortestCoprimeSegment.shortestCoprimeSegment(5, new long[]{4, 6, 1, 3, 6})); | ||
assertEquals(1, ShortestCoprimeSegment.shortestCoprimeSegment(1, new long[]{1})); | ||
} | ||
|
||
@Test | ||
public void testNoCoprimeSegment() { | ||
// There may not be a coprime segment | ||
assertEquals(-1, ShortestCoprimeSegment.shortestCoprimeSegment(5, new long[]{4, 6, 8, 12, 8})); | ||
assertEquals(-1, ShortestCoprimeSegment.shortestCoprimeSegment(10, new long[]{4, 4, 4, 4, 10, 4, 6, 8, 12, 8})); | ||
assertEquals(-1, ShortestCoprimeSegment.shortestCoprimeSegment(1, new long[]{100})); | ||
assertEquals(-1, ShortestCoprimeSegment.shortestCoprimeSegment(3, new long[]{2, 2, 2})); | ||
|
||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.