Skip to content

Commit

Permalink
Prepare for publication
Browse files Browse the repository at this point in the history
  • Loading branch information
spannm committed Jul 3, 2024
1 parent 94dab56 commit a210ab4
Show file tree
Hide file tree
Showing 70 changed files with 97 additions and 438 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@
.~lock*
*.kate-swp
**/Migrate*.java
**/RenameMethodParms.java
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023- Markus S.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
## Java Solutions to Leetcode Problems

In this repo you will find a collection of 2500+ Java solutions to Leetcode coding problems and unit tests.

I participated in Leetcode for quite some time, <br>
peaking in a 500-day streak of solving the daily challenge, <br>
even earning a free T-Shirt (which turned out to kind of small and could not be exchanged for a larger one unless shipped back to China :)

<figure>
<img src="src/test/resources/img/my-leetcode-streak.jpeg" alt="Streak">
<figcaption>500-Day Streak</figcaption>
</figure>

Most solutions have been successfully submitted. <br>
Many come with JUnit tests using test data found in the problem descriptions.

This project requires Maven and Java 17.<br>
It has neither compile nor run-time, only test dependencies.<br>
Unit tests are based on JUnit 5 and @ParameterizedTest.<br>
The code is structured as a typical standard Maven project and fairly self-explanatory.<br>
Solutions are named *ProblemNNNN*, tests are named *ProblemNNNNTest*<br>
where *NNNN* is the problem number formatted to four digits.<br>
To build the project simply type: `mvn` (defaults to `mvn clean verify`)

- Use as you wish and as you feel fit.<br>

- No warranty given.<br>

- No need to give credit.<br>

Hope you will find it useful.

### Happy coding!

<figure>
<img src="src/test/resources/img/my-leetcode-tee.jpeg" alt="Free Tee">
<figcaption>My free T-Shirt (says 'Large' but fits like 'Medium')</figcaption>
</figure>
17 changes: 11 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,23 @@
<packaging>jar</packaging>

<name>${project.artifactId}</name>
<description>Solutions to Leetcode coding problems.</description>
<description>2500+ solutions to Leetcode coding problems</description>
<url>/~https://github.com/${developerId}/${project.artifactId}</url>
<inceptionYear>2023</inceptionYear>

<licenses>
<license>
<name>MIT License</name>
<url>${project.url}/blob/master/LICENSE</url>
</license>
</licenses>

<developers>
<developer>
<id>${developerId}</id>
<name>Markus Spann</name>
<name>Markus S.</name>
<email>spannm@outlook.de</email>
<organizationUrl>/~https://github.com/${developerId}/</organizationUrl>
<timezone>+1</timezone>
</developer>
</developers>

Expand Down Expand Up @@ -121,6 +127,7 @@
<defaultGoal>clean verify</defaultGoal>

<pluginManagement>

<plugins>

<plugin>
Expand Down Expand Up @@ -154,8 +161,6 @@
</plugins>
</pluginManagement>

<plugins/>

</build>

<profiles>
Expand All @@ -168,7 +173,7 @@
<properties>
<!-- skip _compiling_ the tests -->
<maven.test.skip>true</maven.test.skip>
<!-- skip the tests -->
<!-- skip test execution -->
<skipTests>true</skipTests>

<maven.javadoc.skip>true</maven.javadoc.skip>
Expand Down
28 changes: 1 addition & 27 deletions src/main/java/io/github/spannm/leetcode/LeetcodeProblem.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,9 @@

public abstract class LeetcodeProblem {

private final boolean doOutput;

protected LeetcodeProblem() {
this(true);
}

protected LeetcodeProblem(boolean _doOutput) {
doOutput = _doOutput;
}

public final boolean doOutput() {
return doOutput;
}

public final void printf(String _format, Object... _args) {
if (doOutput) {
System.out.printf(_format, _args);
}
}

public final void println(Object _arg) {
if (doOutput) {
System.out.println(_arg);
}
}

@Override
public String toString() {
return getClass().getSimpleName() + "[]";
return String.format("%s[]", getClass().getSimpleName());
}

public static String asString(Object _o) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ public abstract class LeetcodeSqlProblem extends LeetcodeProblem {
private final String sql;

protected LeetcodeSqlProblem(String _sql) {
super(true);
sql = _sql;
}

Expand Down
7 changes: 1 addition & 6 deletions src/main/java/io/github/spannm/leetcode/dep/Sudoku.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,7 @@ public boolean solve(Board _board) {

List<Field> fields = _board.boxes.stream().flatMap(b -> b.getFields().stream()).toList();

// inspect field by field
for (Field currFld : fields) {
// if (currFld.getRowNo() == 'A' && currFld.getColNo() == 1) {
// doOutput(" DEBUG ");
// }
// doOutput(" %s%n", currFld);
for (Field currFld : fields) { // inspect field by field

// check all remaining possible values whether one is only possible in this field
for (Area area : currFld.getAreas()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,23 @@

import io.github.spannm.leetcode.LeetcodeProblem;

import java.util.ArrayList;
import java.util.List;

/**
* <a href="https://leetcode.com/problems/two-sum/">1. Two Sum</a>.
*/
class Problem0001 extends LeetcodeProblem {

int[] twoSum(int[] _nums, int _target) {
if (doOutput()) {
printf("Input: %s, target: %d%n", java.util.Arrays.toString(_nums), _target);
}
return impl1(_nums, _target);
}

int[] impl1(int[] _nums, int _target) {
final java.util.List<IdxAndNum> idxAndNums = new java.util.ArrayList<>();
List<IdxAndNum> idxAndNums = new ArrayList<>();
for (int i = 0; i < _nums.length; i++) {
idxAndNums.add(new IdxAndNum(i, _nums[i]));
}
idxAndNums.sort(java.util.Comparator.comparing(IdxAndNum::getNum).thenComparing(IdxAndNum::getIdx));

final int len = idxAndNums.size();

if (doOutput()) {
printf("Values (%s): %s%n", len, idxAndNums);
}

int[] result = null;

for (int i1 = 0; i1 < len - 1; i1++) {
Expand All @@ -40,19 +32,14 @@ int[] impl1(int[] _nums, int _target) {

}

System.err.printf("No result found! %n%n");
return null;
}

/**
* Calculates the sum of two values.<br>
* If equal to {@code target}, returns their indices in an int array.
*/
int[] calcSum(IdxAndNum _in1, IdxAndNum _in2, int _target) {
if (doOutput()) {
printf(" Test %s + %s = %s %n%n", _in1, _in2, _target);
}

static int[] calcSum(IdxAndNum _in1, IdxAndNum _in2, int _target) {
if (_in1.getNum() + _in2.getNum() == _target) {
return new int[] {_in1.getIdx(), _in2.getIdx()};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,18 @@
class Problem0004 extends LeetcodeProblem {

double findMedianSortedArrays(int[] _nums1, int[] _nums2) {
final LinkedList<Integer> l1 = Arrays.stream(_nums1).boxed().collect(Collectors.toCollection(LinkedList::new));
final LinkedList<Integer> l2 = Arrays.stream(_nums2).boxed().collect(Collectors.toCollection(LinkedList::new));
LinkedList<Integer> l1 = Arrays.stream(_nums1).boxed().collect(Collectors.toCollection(LinkedList::new));
LinkedList<Integer> l2 = Arrays.stream(_nums2).boxed().collect(Collectors.toCollection(LinkedList::new));

// merge sorted arrays into one
final LinkedList<Integer> merged = new LinkedList<>();
// Solange noch nicht beide Listen hinzugefügt worden
while (!l1.isEmpty() && !l2.isEmpty()) {
if (l1.getFirst() <= l2.getFirst()) {
merged.addLast(l1.removeFirst());
} else {
merged.addLast(l2.removeFirst());
}
}
// Füge Rest hinzu, falls etwas übrig ist.
merged.addAll(l1);
merged.addAll(l2);

Expand All @@ -46,15 +44,9 @@ List<Integer> merge(LinkedList<Integer> _l1, LinkedList<Integer> _l2) {
merged.addLast(_l2.removeFirst());
}
}
// Füge Rest hinzu, falls etwas übrig ist.
merged.addAll(_l1);
merged.addAll(_l2);
return merged;
}

public void printFindMedianSortedArrays(int[] _nums1, int[] _nums2) {
double result = findMedianSortedArrays(_nums1, _nums2);
printf("%s and %s => %s%n", asString(_nums1), asString(_nums2), result);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ String convert(String _s, int _numRows) {

for (int i = 0; i < arr.length; i++) {
sbs.get(z).append(arr[i]);
printf("i=%s, z=%s, v=%s %s %n", i, z, arr[i], up ? "up" : "down");
if (up) {
z++;
} else {
Expand All @@ -34,10 +33,6 @@ String convert(String _s, int _numRows) {
}
}

if (doOutput()) {
sbs.forEach(this::println);
}

return sbs.stream().map(StringBuilder::toString).collect(Collectors.joining(""));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
class Problem0008 extends LeetcodeProblem {

int myAtoi(String _s) {
printf("Input: %s %n", _s);
if (_s == null || _s.isEmpty()) {
return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ public List<String> letterCombinations2(String _digits) {
Set<String> combinations = new LinkedHashSet<>();

generatePermutations(lol, combinations, 0, "");
printf("Combinations: %s %n", combinations);

return new ArrayList<>(combinations);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
class Problem0019 extends LeetcodeProblem {

ListNode removeNthFromEnd(ListNode _head, int _n) {
printf("Input: %s, n=%d%n", _head, _n);
ListNode node = _head;

int count = 1;
Expand All @@ -25,7 +24,6 @@ ListNode removeNthFromEnd(ListNode _head, int _n) {
}

int position = count - _n + 1; // position to remove
printf("Position of node to remove: %d (%d from end)%n", position, _n);
if (position == 1) {
_head = _head.next;
return _head;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ int searchInsert(int[] _nums, int _target) {
}

int searchInsert1(int[] _nums, int _target, int _fromIndex, int _toIndex) {
printf("%s, target %d, from %d to %d %n", java.util.Arrays.toString(_nums), _target, _fromIndex, _toIndex);
if (_target < _nums[_fromIndex]) {
return _fromIndex;
} else if (_target > _nums[_toIndex]) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@ void solveSudoku(char[][] _board) {
Sudoku.Board b = new Sudoku.Board(getClass().getSimpleName(), _board);
solver.solve(b);
b.updateBoardMatrix(_board);

printf("Board one-liner: %s%n", b.toString("", ""));

for (Sudoku.Field f : b.getEmptyFields()) {
printf(" Solved: %s%n", f);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
class Problem0057 extends LeetcodeProblem {

int[][] insert(int[][] _intervals, int[] _newInterval) {
printf("intervals: %s, new: %s%n", asString(_intervals), asString(_newInterval));

int arrLen = _intervals == null ? 0 : _intervals.length;
if (arrLen == 0) {
Expand All @@ -39,7 +38,6 @@ int[][] insert(int[][] _intervals, int[] _newInterval) {
int[] mergeInterval = null;
for (int i = 0; i < arrLen; i++) {
int[] currInterval = _intervals[i];
printf("Current: %s%n", asString(currInterval));

if (_newInterval[0] >= currInterval[0] && _newInterval[1] <= currInterval[1]) { // within
return _intervals;
Expand All @@ -57,14 +55,12 @@ int[][] insert(int[][] _intervals, int[] _newInterval) {
}
} else if (mergeInterval != null) { // currently merging
if (mergeInterval[1] < currInterval[0]) {
printf("Merge done, end interval: %s%n", mergeInterval[1]);
intervalList.add(mergeInterval);
intervalList.addAll(List.of(_intervals).subList(i, arrLen));
break;
} else if (i == arrLen - 1) { // last
mergeInterval[1] = Math.max(mergeInterval[1], currInterval[1]);
intervalList.add(mergeInterval);
printf("Merge done, end interval: %s%n", mergeInterval[1]);
break;
} else {
mergeInterval[1] = Math.max(mergeInterval[1], currInterval[1]);
Expand All @@ -73,17 +69,14 @@ int[][] insert(int[][] _intervals, int[] _newInterval) {
} else {
mergeInterval = new int[] {Math.min(currInterval[0], _newInterval[0]), Math.max(currInterval[1], _newInterval[1])
};
printf("Merging, begin interval: %s%n", mergeInterval[0]);
if (i == arrLen - 1) { // last
intervalList.add(mergeInterval);
printf("Merge done, end interval: %s%n", mergeInterval[1]);
break;
}
}

}
_intervals = intervalList.toArray(new int[0][]);
printf("Returning %s%n", asString(_intervals));
return _intervals;
}

Expand Down
Loading

0 comments on commit a210ab4

Please sign in to comment.