Search code examples
javaalgorithmdata-structuresdynamic-arrays

how to find latest element added or deleted in dynamic array


I am getting an input array in loop which contains numbers in sorted order. on Every iteration the input array will either be added or be deleted with any one number (no duplicates in input array). Example

1st iteration: Input Array [3,4,8,19]
2nd iteration: Input Array [3,4,5,8,19]
Output: 5 added
3rd iteration: Input Array [3,4,5,8,19,40]
Output: 40 added
4th iteration: Input Array [3,5,8,19,40]
Output: 4 deleted
5th iteration: Input Array [1,3,5,8,19,40]
Output: 1 added

Note: I have a solution where I can take a map or different array and copy the input array in new array then from next iteration onward I'm going to iterate input array and compare the input array's elements with new array, the one not present in new array is the one added; and the one present in new array but not present in input array is the one deleted. I am looking for a better approach with most optimized logic in terms of space and time.


Solution

  • Given below is one of the simplest ways:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int first[] = { 3, 4, 8, 19 };
            int second[] = { 3, 4, 5, 8, 19 };
            int diff = Arrays.stream(second).sum() - Arrays.stream(first).sum();
            System.out.println(Math.abs(diff) + (diff > 0 ? " added." : diff < 0 ? " deleted." : ""));
        }
    }
    

    Output:

    5 added.
    

    Demo:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[][] testArrs = { 
                    { 3, 4, 8, 19 }, 
                    { 3, 4, 5, 8, 19 }, 
                    { 3, 4, 5, 8, 19, 40 }, 
                    { 3, 5, 8, 19, 40 },
                    { 1, 3, 5, 8, 19, 40 } };
            int i, diff = 0, lastSum = Arrays.stream(testArrs[0]).sum(), currentSum;
    
            for (i = 1; i < testArrs.length; i++) {
                currentSum = Arrays.stream(testArrs[i]).sum();
                diff = currentSum - lastSum;
                System.out.println(Math.abs(diff) + (diff > 0 ? " added." : diff < 0 ? " deleted." : ""));
                lastSum = currentSum;
            }
        }
    }
    

    Output:

    5 added.
    40 added.
    4 deleted.
    1 added.