Skip to content

Commit

Permalink
Add Codility missing element (Go/Java)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuamegnauth54 committed May 12, 2024
1 parent af00c44 commit 32c181e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Go/jobspls/algorithms/perm_missing_element.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package algorithms

func PermMissingElement(haystack []int) uint {
hayset := make(map[int]struct{}, len(haystack))

for _, v := range haystack {
hayset[v] = struct{}{}
}

// Will always return at least element because the loop goes to
// one past haystack's length
for i := 1; i < len(haystack) + 2; i++ {
if _, found := hayset[i]; !found {
return uint(i)
}
}

panic("Unreachable")
}

21 changes: 21 additions & 0 deletions Java/jobspls/algorithms/PermMissingElement.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package jobspls.algorithms;

import java.util.Arrays;
import java.util.TreeSet;

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PermMissingElement {
public static int missing_element(int[] haystack) {
var hayset = new TreeSet<Integer>(Arrays.stream(haystack)
.boxed()
.collect(Collectors.toList()));

// Should always find a value.
return IntStream.range(1, haystack.length + 2)
.filter(n -> { return !hayset.contains(n); })
.findFirst()
.getAsInt();
}
}

0 comments on commit 32c181e

Please sign in to comment.