Skip to content

Instantly share code, notes, and snippets.

class LargestComponentSizeByCommonFactor {
private int[] parent;
public int largestComponentSize(int[] A) {
int maxVal = 1;
for (int num : A) {
if (num > maxVal) {
maxVal = num;
}
class FindRightInterval {
public int[] findRightInterval(int[][] intervals) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int[] interval : intervals) {
if (min > interval[0]) {
min = interval[0];
}
if (max < interval[1]) {
max = interval[1];
class ReorderList {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
class FizzBuzz {
public List<String> fizzBuzz(int n) {
List<String> fizzBuzz = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) {
fizzBuzz.add("FizzBuzz");
} else if (i % 5 == 0) {
fizzBuzz.add("Buzz");
} else if (i % 3 == 0) {
class MinimumCostForTickets {
public int mincostTickets(int[] days, int[] costs) {
int maxDays = days[days.length - 1];
int[] dp = new int[maxDays + 1];
int index = 0;
for (int d = 1; d <= maxDays; d++) {
dp[d] = dp[d - 1];
if (d == days[index]) {
int oneDayPass = dp[d - 1] + costs[0];
int sevenDayPass = dp[Math.max(0, d - 7)] + costs[1];
class SumOfLeftLeaves {
private int leavesSum;
public int sumOfLeftLeaves(TreeNode root) {
leavesSum = 0;
dfs(root, false);
return leavesSum;
}
class DistributeCandiesToPeople {
public int[] distributeCandies(int candies, int num_people) {
int n = num_people;
int turns = 0;
int sum = n * (n + 1) / 2;
int n2 = n * n;
while (sum <= candies) {
candies -= sum;
sum += n2;
turns++;
class NonOverlappingIntervals {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[1] - b[1]);
int erase = 0;
int end = Integer.MIN_VALUE;
for (int[] interval : intervals) {
if (end > interval[0]) {
erase++;
} else {
end = interval[1];
class LongestPalindrome {
public int longestPalindrome(String s) {
int[] count = new int[128];
for (char c : s.toCharArray()) {
count[c]++;
}
int odds = 0;
for (char c = 'A'; c <= 'z'; c++) {
if (count[c] % 2 == 1) {
odds++;
class CombinationIterator {
private Queue<String> queue;
public CombinationIterator(String characters, int combinationLength) {
queue = new LinkedList<>();
generateCombinations(new char[combinationLength], 0,
characters.toCharArray(), 0, combinationLength, queue);
}