export const nearestPerfectMonths = (year: number) => {
const result = { prev: new Date(year, 0, 1), next: new Date(year + 1, 0, 1) };
while (![4, 5].includes(result.prev.getDay())) {
result.prev = new Date(result.prev.getFullYear() - 1, 0, 1);
}
while (![4, 5].includes(result.next.getDay())) {
result.next = new Date(result.next.getFullYear() + 1, 0, 1);
}
return {
prev: `${result.prev.getFullYear()}-02`,
next: `${result.next.getFullYear()}-02`,
};
};
github.com/muhammadk160...
02.02.2026 12:23
π 2
π 0
π¬ 0
π 0
const countVowels = (word: string) => word.match(/[aeiou]/gi)?.length || 0;
export const flippedy = (str: string) => {
const words = str.split(" ");
const firstWord = words[0];
if (!firstWord) return str;
const vowelCount = countVowels(firstWord);
return words.reduce((acc, word) => {
if (countVowels(word) === vowelCount) {
return acc + " " + word.split("").reverse().join("");
}
return acc + " " + word;
});
};
github.com/muhammadk160...
26.01.2026 10:52
π 3
π 0
π¬ 0
π 0
export const hungryBears = (bears: { name: string; hunger: number }[]) =>
bears
.filter(bear => bear.hunger > bears.reduce((sum, bear) => sum + bear.hunger, 0) / bears.length)
.sort((a, b) => a.name.localeCompare(b.name))
.map(bear => bear.name);
github.com/muhammadk160...
I consider this a one-liner, :)
12.01.2026 09:49
π 3
π 0
π¬ 0
π 0
export const sumOfNeighbors = (arr: number[]): number => {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += (arr[i - 1] || 0) + (arr[i] || 0) + (arr[i + 1] || 0);
}
return sum;
};
github.com/muhammadk160...
08.09.2025 06:32
π 3
π 0
π¬ 0
π 0
export const canFormHexagon = (sides: number[]): boolean => {
if (sides.length !== 6) return false;
const sideCount: Record<number, number> = {};
for (const side of sides) {
sideCount[side] = (sideCount[side] || 0) + 1;
}
return Object.values(sideCount).filter(count => count >= 2).length === 3;
};
github.com/muhammadk160...
Hexagons are Bestagons!
28.07.2025 08:21
π 2
π 0
π¬ 0
π 0
export const nonRepeat = (str: string): string => {
const charCount: Record<string, number> = {};
for (const char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let i = str.length - 1; i >= 0; i--) {
const char = str[i] || "";
if (charCount[char] === 1) return char;
}
return "";
};
github.com/muhammadk160...
30.06.2025 09:11
π 2
π 0
π¬ 0
π 0
const ROMAN_MAP = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
} as const;
const romanToInt = (roman: string): number => {
let total = 0;
let prevValue = 0;
for (let i = roman.length - 1; i >= 0; i--) {
const currentValue = ROMAN_MAP[roman[i] as keyof typeof ROMAN_MAP];
if (currentValue < prevValue) total -= currentValue;
else total += currentValue;
prevValue = currentValue;
}
return total;
};
export const sortMonarchs = (monarchs: string[]): string[] => {
return monarchs.sort((a, b) => {
const [nameA, ordinalA] = a.split(" ") as [string, string];
const [nameB, ordinalB] = b.split(" ") as [string, string];
const numberA = romanToInt(ordinalA);
const numberB = romanToInt(ordinalB);
// If years are the same, compare by name
return nameA.localeCompare(nameB) || numberA - numberB;
});
};
github.com/muhammadk160...
16.06.2025 07:23
π 2
π 0
π¬ 0
π 0
FastAPI - Swagger UI
I just released a new publicly available API
This API bridges that gap.
- Programmatic access to SBP daily weighted average buying rates (in JSON format)
- Updated daily at 4:00 PM PKT (excluding Bank Holidays)
- Built with FastAPI
Try it out: sbp-war-api.muhammadkhan.dev/docs
13.06.2025 15:44
π 1
π 2
π¬ 1
π 0
export type TrafficLight = "red" | "green" | "yellow";
export const isValidTrafficSequence = (sequence: TrafficLight[]): boolean => {
let prevLight: TrafficLight | null = null;
for (let i = 0; i < sequence.length; i++) {
const light = sequence[i] as TrafficLight;
if (prevLight === "red" && light !== "green") return false;
if (prevLight === "green" && light !== "yellow") return false;
if (prevLight === "yellow" && light !== "red") return false;
prevLight = light;
}
return true;
};
github.com/muhammadk160...
10.06.2025 06:39
π 1
π 0
π¬ 0
π 0
export const nestArray = (array: any[]): any[] => {
const result: any[] = [];
let current = result;
for (let i = 0; i < array.length; i++) {
current.push(array[i]);
if (i === array.length - 1) break;
const nextLevel: any[] = [];
current.push(nextLevel);
current = nextLevel;
}
return result;
};
github.com/muhammadk160...
I have only one question regarding this task: "But why?"
02.06.2025 12:50
π 3
π 0
π¬ 1
π 0
export const oddSum = (first: number[], second: number[]): number[][] => {
const result: number[][] = [];
first.forEach(x => {
second.forEach(y => {
if ((x + y) % 2 !== 0) {
result.push([x, y]);
}
});
});
return result;
};
github.com/muhammadk160...
30.05.2025 13:29
π 3
π 0
π¬ 0
π 0
const CORNER = "+";
const VERTICAL = "|";
const HORIZONTAL = "-";
const DIAGONAL = "/";
const SPACE = " ";
const NUMBER_OF_HORIZONTAL_LINES = 3;
export const drawCube = (size: number) => {
const horizontalLine = Array.from({ length: size * 2 + 2 })
.map((_, i, { length }) => (i === 0 || i === length - 1 ? CORNER : HORIZONTAL))
.join("");
const padding = Math.floor(size / 2);
const rows = Array.from({ length: size + NUMBER_OF_HORIZONTAL_LINES + padding });
return (
"\n" +
rows
.map((_, i, { length }) => {
if (i === 0) {
return SPACE.repeat(padding + 1) + horizontalLine;
} else if (i > 0 && i < padding + 1) {
return (
SPACE.repeat(padding + 1 - i) +
DIAGONAL +
SPACE.repeat(size * 2) +
DIAGONAL +
SPACE.repeat(Math.max(i - 1, 0)) +
VERTICAL
);
} else if (i === padding + 1) {
return horizontalLine + SPACE.repeat(padding) + VERTICAL;
} else if (i > padding + 1 && i < length - 1) {
let endItem = VERTICAL;
let paddingEnd = padding;
if (i === size + 1) {
endItem = CORNER;
}
if (i > size + 1) {
endItem = DIAGONAL;
paddingEnd = length - i - 2;
}
return VERTICAL + SPACE.repeat(size * 2) + VERTICAL + SPACE.repeat(paddingEnd) + endItem;
} else if (i === length - 1) {
return horizontalLine;
} else {
return SPACE;
}
})
.join("\n") +
"\n"
);
};
Baseline shamelessly "borrowed" from @tenzhiyang.com
github.com/muhammadk160...
20.05.2025 06:14
π 3
π 0
π¬ 0
π 0
export const addOperators = (origin: number, target: number): string[] => {
const digits = origin.toString().split("");
const result: string[] = [];
const dfs = (index: number, path: string, currentNumber: number) => {
if (index === digits.length) {
if (currentNumber === target) result.push(path);
return;
}
for (let i = index; i < digits.length; i++) {
const digit = digits[i];
const newNumber = Number(digit);
dfs(i + 1, `${path}+${digit}`, currentNumber + newNumber);
dfs(i + 1, `${path}-${digit}`, currentNumber - newNumber);
// Multiply but only if BODMAS is not violated
if (!(path.includes("+") || path.includes("-")))
dfs(i + 1, `${path}*${digit}`, currentNumber * newNumber);
}
};
// Start DFS from the first digit
const firstDigit = digits[0] as string;
const firstNumber = Number(firstDigit);
dfs(1, firstDigit, firstNumber);
return result;
};
github.com/muhammadk160...
16.05.2025 12:26
π 1
π 0
π¬ 0
π 0
"Never think that war, no matter how necessary, nor how justified, is not a crime." ~ Ernest Hemingway
I wish for calmer heads to prevail.
07.05.2025 11:49
π 1
π 0
π¬ 0
π 0
No worries, we all get it.
If anything confusing requirements add to the realism. π€£
06.05.2025 18:48
π 5
π 0
π¬ 1
π 0
export const longestCommonPrefix = (strings: string[]): string => {
let prefix = strings[0] || "";
for (let i = 1; i < strings.length; i++) {
while (strings[i]?.indexOf(prefix) !== 0) {
prefix = prefix.slice(0, -1);
if (prefix === "") return "";
}
}
return prefix;
};
github.com/muhammadk160...
05.05.2025 10:56
π 1
π 0
π¬ 0
π 0
This is what I assumed, since the example function is being called "longestCommonPrefix".
05.05.2025 10:55
π 0
π 0
π¬ 1
π 0
export const compress = (characters: string[]): string[] => {
const compressed: string[] = [];
let currentChar = characters[0] as string;
let count = 1;
for (let i = 1; i <= characters.length; i++) {
if (characters[i] === currentChar) {
count++;
} else {
compressed.push(currentChar);
if (count > 1) {
compressed.push(count.toString());
}
currentChar = characters[i] as string;
count = 1;
}
}
return compressed;
};
github.com/muhammadk160...
28.04.2025 07:44
π 3
π 0
π¬ 0
π 0
List comprehensions π
23.04.2025 05:51
π 2
π 0
π¬ 0
π 0
export type TIngredient = {
name: string;
amount: number;
};
export const calculateIngredients = (
ingredients: TIngredient[],
targetServings: number,
): TIngredient[] =>
ingredients.map(ingredient => ({
...ingredient,
amount: ingredient.amount * targetServings,
}));
github.com/muhammadk160...
21.04.2025 07:43
π 3
π 0
π¬ 0
π 0
const DIRECTIONS = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
] as const;
export const largestPathSum = (grid: number[][]): number => {
const rows = grid.length;
if (!grid[0]) return 0;
const cols = grid[0].length;
let maxSum = 0;
function dfs(x: number, y: number, visited: boolean[][], currentSum: number) {
maxSum = Math.max(maxSum, currentSum);
for (const [dx, dy] of DIRECTIONS) {
const nx = x + dx;
const ny = y + dy;
if (!visited[nx] || !grid[nx]) continue;
if (nx >= 0 && ny >= 0 && nx < rows && ny < cols && !visited[nx][ny]) {
visited[nx][ny] = true;
dfs(nx, ny, visited, currentSum + (grid[nx][ny] || 0));
visited[nx][ny] = false;
}
}
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
// @ts-ignore
visited[i][j] = true;
// @ts-ignore
dfs(i, j, visited, grid[i][j]);
}
}
return maxSum;
};
I am starting to think that noUncheckedIndexedAccess rule is overkill.
github.com/muhammadk160...
16.04.2025 10:33
π 2
π 0
π¬ 0
π 0
const getLeylandNumbers = (n: number): number[] => {
let count = n;
let leylandNumbers: number[] = [];
let x = 2;
while (count > 0) {
for (let i = 2; i <= x; i++) {
leylandNumbers.push(Math.pow(i, x) + Math.pow(x, i));
}
x++;
count--;
}
return leylandNumbers.toSorted((a, b) => a - b).slice(0, n);
};
github.com/muhammadk160...
07.04.2025 09:14
π 2
π 0
π¬ 0
π 0
No, you aren't wrong. That example is incorrect.
01.04.2025 15:23
π 1
π 0
π¬ 1
π 0
const getMinutes = (time: string): number => {
const [hours, minutes] = time.split(":").map(Number);
if (hours === undefined || minutes === undefined)
throw new Error(`Invalid time format: ${time}`);
return hours * 60 + minutes;
};
export const findLongestTimeGap = (times: string[]): number => {
let longestGap = 0;
for (let i = 0; i < times.length - 1; i++) {
const current = times[i] as string;
const next = times[i + 1] as string;
longestGap = Math.max(longestGap, getMinutes(next) - getMinutes(current));
}
return longestGap;
};
github.com/muhammadk160...
01.04.2025 06:56
π 2
π 0
π¬ 0
π 0
export const findLongestStreak = (values: boolean[]) => {
let max = 0;
for (let i = 0; i < values.length; i++) {
let current = 0;
while (values[i]) {
current++;
i++;
}
if (current > max) {
max = current;
}
}
return max;
}
github.com/muhammadk160...
25.03.2025 10:09
π 1
π 0
π¬ 0
π 0
const SEMITONES = {
C: 0,
D: 2,
E: 4,
F: 5,
G: 7,
A: 9,
B: 11,
};
export const findLargestInterval = (keys: string[]): number => {
const intervals = keys.map(key => {
const note = key[0] as keyof typeof SEMITONES;
const octave = Number(key[1]);
return SEMITONES[note] + octave * 12;
});
let largestInterval = 0;
for (let i = 0; i < intervals.length - 1; i++) {
const current = intervals[i] as number;
const next = intervals[i + 1] as number;
largestInterval = Math.max(largestInterval, Math.abs(current - next));
}
return largestInterval;
};
Thanks for forcing me to learn some basic Music Theory π
github.com/muhammadk160...
11.03.2025 07:33
π 3
π 0
π¬ 1
π 0
This has better documentation than half of the production code I write. π
Gorgeous.
11.03.2025 07:31
π 3
π 0
π¬ 1
π 0
export const calculatePrice = (closingDate: string, visitDate: string, price: number): number => {
const closingDateTimestamp = new Date(closingDate).getTime();
const visitDateTimestamp = new Date(visitDate).getTime();
if (visitDateTimestamp > closingDateTimestamp) return price;
const weeks = Math.floor(
(closingDateTimestamp - visitDateTimestamp) / (1000 * 60 * 60 * 24 * 7),
);
for (let i = 0; i < weeks; i++) {
price -= price * 0.1;
}
return price;
};
github.com/muhammadk160...
Skipped last week's problem since I felt like the solution I came up with wasn't mine. π
03.03.2025 08:32
π 2
π 0
π¬ 0
π 0