I have written the code for Rotat Array problem, please see the description in the following link:
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/646/
I am facing two problems
Problem 1
The problem is that with following code, i able to pass test case on "Run Code" button but on submit it gives me error that Time exceeded the allowed limit. Please check my code below:
for(int r=0;r<k;r++){
int lastNumber = nums[nums.length-1];
for(int i=nums.length-1;i>0;i--){
nums[i] = nums[i-1];
}
nums[0] = lastNumber;
}Problem 2
I changed my logic and tried it with recursion, to achieve time complexity of O(n) becuse my recurrsive code is called n times.
here is the code
class Solution {
public void rotate(int[] nums, int k) {
setPosition(1,nums[nums.length-k],0,nums,k);
}
public static void setPosition(int c, int value, int index, int[] nums, int k){
if(c < nums.length) {
int next_index = c + k < nums.length ? c + k : (c + k) - nums.length;
int next_value = nums[c];
setPosition(c + 1, next_value, next_index, nums, k);
}
nums[index] = value;
}
}The problem with this solution is I am getting correct output in my Intellij IDE but incorrect in leetcode editor
for input:
[1,2,3,4,5,6,7]
3
IntelliJ output: [5,6,7,1,2,3,4]
LeetCode output: [5,6,7,4,2,3,4]
Can anyone please explain my both problems.