Skip to content

Commit

Permalink
Add palindrome and two sums problems
Browse files Browse the repository at this point in the history
  • Loading branch information
xtenzQ committed Jun 28, 2024
1 parent f766248 commit ef59cef
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.xtenzq.arrays;

public class TwoPointers {

public static boolean isPalindrome(String input) {
int start = 0;
int end = input.length() - 1;
while (start < end) {
if (input.charAt(start) != input.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}

public static boolean canBeSummed(int[] sortedArray, int target) {
int start = 0;
int end = sortedArray.length - 1;
while (start < end) {
int sum = sortedArray[start] + sortedArray[end];
if (sum == target) {
return true;
}
if (sum > target) {
end--;
} else {
start++;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.xtenzq.arrays;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class TwoPointersTest {

@Test
void shouldReturnTrueIfPalindrome() {
assertTrue(TwoPointers.isPalindrome("racecar"));
}

@Test
void shouldReturnFalseIfNotPalindrome() {
assertFalse(TwoPointers.isPalindrome("raceacar"));
}

@Test
void shouldReturnTrueIfCanBeSummed() {
assertTrue(TwoPointers.canBeSummed(new int[] { 1, 2, 4, 6, 8, 9, 14, 15 }, 13));
}

@Test
void shouldReturnFalseIfCantBeSummed() {
assertFalse(TwoPointers.canBeSummed(new int[] { 1, 2, 4, 6, 8, 9, 14, 15 }, 30));
}
}

0 comments on commit ef59cef

Please sign in to comment.