AlgorithmsData StructuresContact
Validate Sub Sequence
Rami Del Toro
Rami Del Toro
August 23, 2021
11 min

Table Of Contents

01
Overview
02
Flow Diagram
03
Time Complexity
04
Space Complexity
05
Java Source Code
06
Solution 1 - With While loop
07
Solution 2 - With For loop
08
Conclusion
Validate Sub Sequence

Given two non-empty arrays of integers, write an algorithm that determines whether the second array is a subsequence of the first one.

Overview

Validate Sub Sequence Algorithm Overview Diagram
Validate Sub Sequence Algorithm Overview Diagram

As long, we keep finding the elements of the arbitrary array in the input array and in order, we are good.

Flow Diagram

Validate Sub Sequence Algorithm Flow Diagram
Validate Sub Sequence Algorithm Flow Diagram

Time Complexity

Worst case scenario. we will need to go through the main array once, that would be O(n) time complexity.

Space Complexity

Space complexity is O(1). That is because we are just using a couple of variables, however the amount of the variables will be the same, for any size of input array. You got to love O(1).

Java Source Code

Solution 1 - With While loop

 public boolean isValidWithWhile(final int[] array,final int[] sequence) {
        var arrayIndex = 0;
        var seqIndex = 0;

        while(arrayIndex < array.length && seqIndex < sequence.length) {
            final var hasFoundMatch = array[arrayIndex] == sequence[seqIndex];

            if(hasFoundMatch) {
                seqIndex++;
            }

            arrayIndex++;
        }

        return seqIndex == sequence.length;
    }

Solution 2 - With For loop

 public boolean isValidWithFor(final int[] array, final int[] sequence) {
        var seqIndex = 0;

        for(int value : array) {
            if(seqIndex == sequence.length) {
                break;
            }

            final var hasFoundMatch = sequence[seqIndex] == value;

            if(hasFoundMatch) {
                seqIndex++;
            }
        }

        return seqIndex == sequence.length;
    }

Conclusion

A sequence works in a way a collection never can.

George Murray

Tags

algorithmsarrayeasy

Related Posts

How to implement the MergeSort Algorithm
How to implement the MergeSort Algorithm
October 10, 2021
25 min
© 2022 Rami Del Toro ,All Rights Reserved.