Anirudh Anirudh - 6 months ago 66
Java Question

Solving codingBat Post4 with one loop in Java

The question is about Solving this problem from codingBat in Java.

Problem Statement:

Given a non-empty array of ints, return a new array containing the elements from the original array that come after the last 4 in the original array. The original array will contain at least one 4. Note that it is valid in Java to create an array of length 0.

post4({2, 4, 1, 2}) → {1, 2}

post4({4, 1, 4, 2}) → {2}

post4({4, 4, 1, 2, 3}) → {1, 2, 3}

Here is my solution:

public int[] post4(int[] nums) {

int lastFour=-1;
int[] post4={};

for(int i=nums.length-1;i>=0;i--)
lastFour=i; //find the index of the last 4 in the array
int newLen=(nums.length-lastFour)-1;
post4=new int[newLen]; //reassign the post4 array with required length

for(int j=0;j<newLen;j++)
post4[j]=nums[lastFour+1]; //assign values from orig. array after last 4

return post4;

But I have used 2 loops. It should be solved using at max one loop. Do not use collections or any wrappers classes.

  • Before iteration create result array, lets say with length 0.
  • Each time you find 4 create new result array with size based on index of that 4 and length of nums to store rest of elements.
  • If number is not 4 place it in result array (don't place if result arrays length is 0 because it means we didn't find any 4 yet, or it was last element of nums array).

Here is example solution

public int[] post4(int[] nums) {

    int[] result = new int[0];

    int j = 0;
    for (int i = 0; i<nums.length; i++){
       if (nums[i] == 4) {
           result = new int[nums.length - i-1];
           if (result.length>0) result[j++] = nums[i]; 

    return result;