Left Rotate Array (In Place)
JavaScript
Medium
5 views
Problem Description
Given an array and a number k, rotate the array to the left by k steps and print the result.
Input Format
Line1: n then n integers. Line2: k.
Output Format
One line: rotated array.
Sample Test Case
Input:
6 10 20 30 40 50 60
2
Output:
30 40 50 60 10 20
Official Solution
const fs=require('fs');const raw=fs.readFileSync(0,'utf8').trim();if(!raw)process.exit(0);const lines=raw.split(/\
?\
/);const p=lines[0].trim().split(/\\s+/);let idx=0;const n=Number(p[idx++]);let arr=[];for(let i=0;i<n;i++)arr.push(Number(p[idx++]));let k=Number((lines[1]||'0').trim());k%=n;const rev=(l,r)=>{while(l<r){const t=arr[l];arr[l]=arr[r];arr[r]=t;l++;r--;}};rev(0,k-1);rev(k,n-1);rev(0,n-1);process.stdout.write(arr.join(' '));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!