7
\$\begingroup\$

The problem I am referring to is here

So basically it's about shifting an array of ints 1 position to the left and relocating the lost first int in the start of the array to the last position at the right:

\$\mathrm{shiftLeft}(\{6, 2, 5, 3\}) → \{2, 5, 3, 6\}\$

\$\mathrm{shiftLeft}(\{1, 2\}) → \{2, 1\}\$

\$\mathrm{shiftLeft}(\{1\}) → \{1\}\$

Please feel free to review the code below:

public int[] shiftLeft(int[] nums) {
    for(int i = 0, start = 0; i < nums.length; i++)
    {
        if(i == 0)
            start = nums[i];
        if(i == (nums.length -1))
        {
            nums[i] = start;
            break;
        }    
        nums[i] = nums[i + 1];
    }
    return nums;            
}

Also I would like to get rid of the variable start and try to solve it only using the loop iterator i, any suggestions are welcome.

\$\endgroup\$
9
\$\begingroup\$

Your current solution is actually pretty good, conceptually. There's nothing wrong with the start variable. I am not sure why you want to remove it. The loop is logically a good solution, but there's a better way than that, though (better because you can make the system do it for you....).

public int[] shiftLeft(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return nums;
    }
    int start = nums[0];
    System.arraycopy(nums, 1, nums, 0, nums.length - 1);
    nums[nums.length - 1] = start;
    return nums;
}

Note that, in addition to using System.arraycopy I also check to see that the input has valid values available....

\$\endgroup\$
  • 1
    \$\begingroup\$ I'd omit the nums == null check. Your method is null-safe, but most Java methods are not, which means that the programmer must handle nulls somewhere. If they don't, they'll get an NPE and the sooner the better. \$\endgroup\$ – maaartinus Apr 6 '15 at 23:04
  • \$\begingroup\$ @rolflWhat if we want to shift it to right? \$\endgroup\$ – paul Nov 30 '15 at 5:16
  • \$\begingroup\$ @paul - then adjust the indices you see in the code to be in the other direction.... so, for example instead of int start = nums[0] have int start = nums[nums.length - 1] \$\endgroup\$ – rolfl Nov 30 '15 at 5:26
  • \$\begingroup\$ what if we want to shift it 50 times to the left but array length is 20!? your solution would have a bug then I'd say. \$\endgroup\$ – Mona Jalal May 1 '16 at 7:17
  • 1
    \$\begingroup\$ @MonaJalal - well, no.... it has no bug. Your comment makes no sense. The original question is to only shift by 1, and there is not even an argument/parameter to specify any other shift distance. The only way to shift by 50 is to call the method 50 times, and it will work just fine then \$\endgroup\$ – rolfl May 1 '16 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.