Skip to content

Instantly share code, notes, and snippets.

View pjcodesjs's full-sized avatar

PJ Codes pjcodesjs

View GitHub Profile
// Using the splice() method:
const arr = [1, 2, 3, 4, 5];
const rotations = 2; // number of times to rotate the array
for (let i = 0; i < rotations; i++) {
const element = arr.splice(0, 1)[0];
arr.push(element);
}
function smallestMissingPositiveNumber(arr) {
arr.sort((a, b) => a - b);
let smallestPositive = 1;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === smallestPositive) {
smallestPositive++;
} else if (arr[i] > smallestPositive) {
return smallestPositive;
}
}
function findTriplets(arr) {
let result = [];
const n = arr.length;
// Sort the array
arr.sort((a, b) => a - b);
for(let i = 0; i < n - 2; i++) {
// Check for duplicates
if (i > 0 && arr[i] === arr[i-1]) {
function longestPalindrome(str) {
let longestPalindrome = "";
for (let i = 0; i < str.length; i++) {
// Check for odd-length palindrome
let left = i;
let right = i;
while (left >= 0 && right < str.length && str[left] === str[right]) {
let palindrome = str.slice(left, right + 1);
if (palindrome.length > longestPalindrome.length) {
function longestConsecutiveSubsequence(arr) {
arr.sort((a, b) => a - b); // Step 1
let longestSubsequence = 1; // Step 2
let currentSubsequence = 1; // Step 3
for (let i = 1; i < arr.length; i++) { // Step 4
if (arr[i] === arr[i - 1] + 1) { // Step 5
currentSubsequence++;
if (currentSubsequence > longestSubsequence) { // Step 6
longestSubsequence = currentSubsequence;
function reverseLinkedList(head) {
let prev = null;
let curr = head;
while (curr !== null) {
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
const originalStr = 'Hello world';
const reversedStr = reverseWords(originalStr);
console.log(reversedStr); // Output: 'world Hello'
function reverseWords(str) {
// Split the string into an array of words
const wordsArr = str.split(' ');
// Reverse the order of the words in the array
const reversedWordsArr = wordsArr.reverse();
// Join the reversed array back into a string
const reversedStr = reversedWordsArr.join(' ');
function maxSubarray(arr, k) {
const result = []; // to store maximum values of subarrays
const queue = []; // to store indices of elements in the current subarray
for (let i = 0; i < arr.length; i++) {
// remove elements that are outside of the current window
if (queue.length > 0 && queue[0] <= i - k) {
queue.shift();
}
function isPalindrome(head) {
let arr = [];
let current = head;
while (current) {
arr.push(current.val);
current = current.next;
}
let i = 0;