Have I achieved linear time complexity O(n) for this array comparison algorithm? EDITED












1















I am writing a method that compares 2 arrays, a and b, and returns "YES" if all the elements of b are present in a, and "NO" otherwise. The algorithm must have linear time complexity. It is assumed that both arrays are sorted and have distinct elements.



I have a solution that works but I am confused about the time complexity. I have used a single foreach to check if the first element in a is an element of b and if it is not, I increment the search index of a and check again. I understand this is O(n).



If the element exists, I then use a while loop to check all the elements of b against the single element of a to see if the element is in both arrays.



Here's the method:



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int bIndex = 0;
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
while (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
break;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}


My question is; have I just mimicked a nested for loop and achieved O(n^2) or is this O(n)? I think it's O(n) but am not sure as I'm still fairly new to this topic.



Many thanks :)



--- EDIT ---



I have re-written it and removed the while loop within the while loop, it still works fine. It seems to me that it now only runs a.length times. Has this changed the time complexity?



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int bIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
if (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}









share|improve this question

























  • This will be O(m*n)

    – Pushpesh Kumar Rajwanshi
    Nov 19 '18 at 15:09











  • check for a= {1,2,3,4,5} and b={5,4,3,2,1} it lead time complexity to a.length * b.length

    – secret super star
    Nov 19 '18 at 15:11













  • Mmm sorry can you explain what O(m*n) entails please? Thanks

    – PumpkinBreath
    Nov 19 '18 at 15:11






  • 2





    Say a has n elements and b has m elements, this makes O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m) because you iterate over a and in the loop, you iterate over b twice but after another. If n = m this will be O(n^2).

    – deHaar
    Nov 19 '18 at 15:11








  • 1





    Sorry should have mentioned that it is assumed that both a and b are sorted and have distinct elements

    – PumpkinBreath
    Nov 19 '18 at 15:40


















1















I am writing a method that compares 2 arrays, a and b, and returns "YES" if all the elements of b are present in a, and "NO" otherwise. The algorithm must have linear time complexity. It is assumed that both arrays are sorted and have distinct elements.



I have a solution that works but I am confused about the time complexity. I have used a single foreach to check if the first element in a is an element of b and if it is not, I increment the search index of a and check again. I understand this is O(n).



If the element exists, I then use a while loop to check all the elements of b against the single element of a to see if the element is in both arrays.



Here's the method:



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int bIndex = 0;
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
while (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
break;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}


My question is; have I just mimicked a nested for loop and achieved O(n^2) or is this O(n)? I think it's O(n) but am not sure as I'm still fairly new to this topic.



Many thanks :)



--- EDIT ---



I have re-written it and removed the while loop within the while loop, it still works fine. It seems to me that it now only runs a.length times. Has this changed the time complexity?



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int bIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
if (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}









share|improve this question

























  • This will be O(m*n)

    – Pushpesh Kumar Rajwanshi
    Nov 19 '18 at 15:09











  • check for a= {1,2,3,4,5} and b={5,4,3,2,1} it lead time complexity to a.length * b.length

    – secret super star
    Nov 19 '18 at 15:11













  • Mmm sorry can you explain what O(m*n) entails please? Thanks

    – PumpkinBreath
    Nov 19 '18 at 15:11






  • 2





    Say a has n elements and b has m elements, this makes O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m) because you iterate over a and in the loop, you iterate over b twice but after another. If n = m this will be O(n^2).

    – deHaar
    Nov 19 '18 at 15:11








  • 1





    Sorry should have mentioned that it is assumed that both a and b are sorted and have distinct elements

    – PumpkinBreath
    Nov 19 '18 at 15:40
















1












1








1








I am writing a method that compares 2 arrays, a and b, and returns "YES" if all the elements of b are present in a, and "NO" otherwise. The algorithm must have linear time complexity. It is assumed that both arrays are sorted and have distinct elements.



I have a solution that works but I am confused about the time complexity. I have used a single foreach to check if the first element in a is an element of b and if it is not, I increment the search index of a and check again. I understand this is O(n).



If the element exists, I then use a while loop to check all the elements of b against the single element of a to see if the element is in both arrays.



Here's the method:



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int bIndex = 0;
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
while (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
break;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}


My question is; have I just mimicked a nested for loop and achieved O(n^2) or is this O(n)? I think it's O(n) but am not sure as I'm still fairly new to this topic.



Many thanks :)



--- EDIT ---



I have re-written it and removed the while loop within the while loop, it still works fine. It seems to me that it now only runs a.length times. Has this changed the time complexity?



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int bIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
if (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}









share|improve this question
















I am writing a method that compares 2 arrays, a and b, and returns "YES" if all the elements of b are present in a, and "NO" otherwise. The algorithm must have linear time complexity. It is assumed that both arrays are sorted and have distinct elements.



I have a solution that works but I am confused about the time complexity. I have used a single foreach to check if the first element in a is an element of b and if it is not, I increment the search index of a and check again. I understand this is O(n).



If the element exists, I then use a while loop to check all the elements of b against the single element of a to see if the element is in both arrays.



Here's the method:



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int bIndex = 0;
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
while (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
break;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}


My question is; have I just mimicked a nested for loop and achieved O(n^2) or is this O(n)? I think it's O(n) but am not sure as I'm still fairly new to this topic.



Many thanks :)



--- EDIT ---



I have re-written it and removed the while loop within the while loop, it still works fine. It seems to me that it now only runs a.length times. Has this changed the time complexity?



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int bIndex = 0;
int elementsFound = 0;
while (aIndex < a.length) {
int value = a[aIndex];
boolean elementExists = false;
for (int i : b) {
if (value == i) {
elementExists = true;
break;
}
}
if (elementExists) {
if (bIndex < b.length) {
if (b[bIndex] == a[aIndex]) {
elementsFound++;
aIndex++;
} else {
bIndex++;
}
}
} else{
aIndex++;
}
}
return elementsFound == b.length ? "YES" : "NO";
}






java arrays time-complexity






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 16:51







PumpkinBreath

















asked Nov 19 '18 at 15:05









PumpkinBreathPumpkinBreath

1189




1189













  • This will be O(m*n)

    – Pushpesh Kumar Rajwanshi
    Nov 19 '18 at 15:09











  • check for a= {1,2,3,4,5} and b={5,4,3,2,1} it lead time complexity to a.length * b.length

    – secret super star
    Nov 19 '18 at 15:11













  • Mmm sorry can you explain what O(m*n) entails please? Thanks

    – PumpkinBreath
    Nov 19 '18 at 15:11






  • 2





    Say a has n elements and b has m elements, this makes O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m) because you iterate over a and in the loop, you iterate over b twice but after another. If n = m this will be O(n^2).

    – deHaar
    Nov 19 '18 at 15:11








  • 1





    Sorry should have mentioned that it is assumed that both a and b are sorted and have distinct elements

    – PumpkinBreath
    Nov 19 '18 at 15:40





















  • This will be O(m*n)

    – Pushpesh Kumar Rajwanshi
    Nov 19 '18 at 15:09











  • check for a= {1,2,3,4,5} and b={5,4,3,2,1} it lead time complexity to a.length * b.length

    – secret super star
    Nov 19 '18 at 15:11













  • Mmm sorry can you explain what O(m*n) entails please? Thanks

    – PumpkinBreath
    Nov 19 '18 at 15:11






  • 2





    Say a has n elements and b has m elements, this makes O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m) because you iterate over a and in the loop, you iterate over b twice but after another. If n = m this will be O(n^2).

    – deHaar
    Nov 19 '18 at 15:11








  • 1





    Sorry should have mentioned that it is assumed that both a and b are sorted and have distinct elements

    – PumpkinBreath
    Nov 19 '18 at 15:40



















This will be O(m*n)

– Pushpesh Kumar Rajwanshi
Nov 19 '18 at 15:09





This will be O(m*n)

– Pushpesh Kumar Rajwanshi
Nov 19 '18 at 15:09













check for a= {1,2,3,4,5} and b={5,4,3,2,1} it lead time complexity to a.length * b.length

– secret super star
Nov 19 '18 at 15:11







check for a= {1,2,3,4,5} and b={5,4,3,2,1} it lead time complexity to a.length * b.length

– secret super star
Nov 19 '18 at 15:11















Mmm sorry can you explain what O(m*n) entails please? Thanks

– PumpkinBreath
Nov 19 '18 at 15:11





Mmm sorry can you explain what O(m*n) entails please? Thanks

– PumpkinBreath
Nov 19 '18 at 15:11




2




2





Say a has n elements and b has m elements, this makes O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m) because you iterate over a and in the loop, you iterate over b twice but after another. If n = m this will be O(n^2).

– deHaar
Nov 19 '18 at 15:11







Say a has n elements and b has m elements, this makes O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m) because you iterate over a and in the loop, you iterate over b twice but after another. If n = m this will be O(n^2).

– deHaar
Nov 19 '18 at 15:11






1




1





Sorry should have mentioned that it is assumed that both a and b are sorted and have distinct elements

– PumpkinBreath
Nov 19 '18 at 15:40







Sorry should have mentioned that it is assumed that both a and b are sorted and have distinct elements

– PumpkinBreath
Nov 19 '18 at 15:40














3 Answers
3






active

oldest

votes


















1














Since you know that the arrays are ordered (see OP's comment on question,) you don't need to mess around with sets or maps to get linear time. Instead, you can just march forward through both arrays at the same time, always advancing aIndex and only advancing bIndex when you find a match. This results in a linear-time algorithm. Worst-case is O(m) where m is the length of the longer array.



Knowing that the arrays are pre-sorted is a big deal. You should probably update your question with that information.



public String subArrayProblem_LinearTime(int a, intb) {
int aIndex = 0;
int bIndex = 0;
while (bIndex < b.length && aIndex < a.length) {
int value = b[bIndex];
int value2 = a[aIndex];
if(value != value2) {
aIndex++;
}
else {
aIndex++;//we can do this since the elements are distinct. If duplicates are possible, don't advance aIndex here.
bIndex++;
}
}
return bIndex == b.length;//did every index in b find a match before we ran out of aIndex?
}


For debugging purposes, it can be nice to easily see the value and value2 variables, but optimally you would just compare "if(b[bIndex] != a[aIndex])" without the extra steps.






share|improve this answer































    3














    No, it is actually O(n*m) as explained in the comment section.



    If you want a hint, I suggest you add each element of a in a hashmap, and iterate all elements of b, to check if they are present in the hashmap.



    Since searching in hashmap has O(1) complexity on average, and you do that n(length of b) times, you would have O(n) time complexity.






    share|improve this answer

































      1














      Let's say, a has n elements and b has m. Then the first iteration over a will have a complexity of O(n) because it will be done n times in the worst case.



      Inside that loop, there are two iterations over b, which are O(m) each and since they are done after another, their complexity is summed up to O(m) + O(m) = O(m + m) = O(m).



      So the entire complexity computes like this:



      O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m)



      If the lengths of a and b are equal, both will have a complexity of O(n) making it =(n*n) = O(n^2).



      To finally answer your question: No, you have not achieved a linear complexity of O(n) with your code.






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377418%2fhave-i-achieved-linear-time-complexity-on-for-this-array-comparison-algorithm%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Since you know that the arrays are ordered (see OP's comment on question,) you don't need to mess around with sets or maps to get linear time. Instead, you can just march forward through both arrays at the same time, always advancing aIndex and only advancing bIndex when you find a match. This results in a linear-time algorithm. Worst-case is O(m) where m is the length of the longer array.



        Knowing that the arrays are pre-sorted is a big deal. You should probably update your question with that information.



        public String subArrayProblem_LinearTime(int a, intb) {
        int aIndex = 0;
        int bIndex = 0;
        while (bIndex < b.length && aIndex < a.length) {
        int value = b[bIndex];
        int value2 = a[aIndex];
        if(value != value2) {
        aIndex++;
        }
        else {
        aIndex++;//we can do this since the elements are distinct. If duplicates are possible, don't advance aIndex here.
        bIndex++;
        }
        }
        return bIndex == b.length;//did every index in b find a match before we ran out of aIndex?
        }


        For debugging purposes, it can be nice to easily see the value and value2 variables, but optimally you would just compare "if(b[bIndex] != a[aIndex])" without the extra steps.






        share|improve this answer




























          1














          Since you know that the arrays are ordered (see OP's comment on question,) you don't need to mess around with sets or maps to get linear time. Instead, you can just march forward through both arrays at the same time, always advancing aIndex and only advancing bIndex when you find a match. This results in a linear-time algorithm. Worst-case is O(m) where m is the length of the longer array.



          Knowing that the arrays are pre-sorted is a big deal. You should probably update your question with that information.



          public String subArrayProblem_LinearTime(int a, intb) {
          int aIndex = 0;
          int bIndex = 0;
          while (bIndex < b.length && aIndex < a.length) {
          int value = b[bIndex];
          int value2 = a[aIndex];
          if(value != value2) {
          aIndex++;
          }
          else {
          aIndex++;//we can do this since the elements are distinct. If duplicates are possible, don't advance aIndex here.
          bIndex++;
          }
          }
          return bIndex == b.length;//did every index in b find a match before we ran out of aIndex?
          }


          For debugging purposes, it can be nice to easily see the value and value2 variables, but optimally you would just compare "if(b[bIndex] != a[aIndex])" without the extra steps.






          share|improve this answer


























            1












            1








            1







            Since you know that the arrays are ordered (see OP's comment on question,) you don't need to mess around with sets or maps to get linear time. Instead, you can just march forward through both arrays at the same time, always advancing aIndex and only advancing bIndex when you find a match. This results in a linear-time algorithm. Worst-case is O(m) where m is the length of the longer array.



            Knowing that the arrays are pre-sorted is a big deal. You should probably update your question with that information.



            public String subArrayProblem_LinearTime(int a, intb) {
            int aIndex = 0;
            int bIndex = 0;
            while (bIndex < b.length && aIndex < a.length) {
            int value = b[bIndex];
            int value2 = a[aIndex];
            if(value != value2) {
            aIndex++;
            }
            else {
            aIndex++;//we can do this since the elements are distinct. If duplicates are possible, don't advance aIndex here.
            bIndex++;
            }
            }
            return bIndex == b.length;//did every index in b find a match before we ran out of aIndex?
            }


            For debugging purposes, it can be nice to easily see the value and value2 variables, but optimally you would just compare "if(b[bIndex] != a[aIndex])" without the extra steps.






            share|improve this answer













            Since you know that the arrays are ordered (see OP's comment on question,) you don't need to mess around with sets or maps to get linear time. Instead, you can just march forward through both arrays at the same time, always advancing aIndex and only advancing bIndex when you find a match. This results in a linear-time algorithm. Worst-case is O(m) where m is the length of the longer array.



            Knowing that the arrays are pre-sorted is a big deal. You should probably update your question with that information.



            public String subArrayProblem_LinearTime(int a, intb) {
            int aIndex = 0;
            int bIndex = 0;
            while (bIndex < b.length && aIndex < a.length) {
            int value = b[bIndex];
            int value2 = a[aIndex];
            if(value != value2) {
            aIndex++;
            }
            else {
            aIndex++;//we can do this since the elements are distinct. If duplicates are possible, don't advance aIndex here.
            bIndex++;
            }
            }
            return bIndex == b.length;//did every index in b find a match before we ran out of aIndex?
            }


            For debugging purposes, it can be nice to easily see the value and value2 variables, but optimally you would just compare "if(b[bIndex] != a[aIndex])" without the extra steps.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 19 '18 at 16:39









            JeutnargJeutnarg

            8941120




            8941120

























                3














                No, it is actually O(n*m) as explained in the comment section.



                If you want a hint, I suggest you add each element of a in a hashmap, and iterate all elements of b, to check if they are present in the hashmap.



                Since searching in hashmap has O(1) complexity on average, and you do that n(length of b) times, you would have O(n) time complexity.






                share|improve this answer






























                  3














                  No, it is actually O(n*m) as explained in the comment section.



                  If you want a hint, I suggest you add each element of a in a hashmap, and iterate all elements of b, to check if they are present in the hashmap.



                  Since searching in hashmap has O(1) complexity on average, and you do that n(length of b) times, you would have O(n) time complexity.






                  share|improve this answer




























                    3












                    3








                    3







                    No, it is actually O(n*m) as explained in the comment section.



                    If you want a hint, I suggest you add each element of a in a hashmap, and iterate all elements of b, to check if they are present in the hashmap.



                    Since searching in hashmap has O(1) complexity on average, and you do that n(length of b) times, you would have O(n) time complexity.






                    share|improve this answer















                    No, it is actually O(n*m) as explained in the comment section.



                    If you want a hint, I suggest you add each element of a in a hashmap, and iterate all elements of b, to check if they are present in the hashmap.



                    Since searching in hashmap has O(1) complexity on average, and you do that n(length of b) times, you would have O(n) time complexity.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 19 '18 at 16:06

























                    answered Nov 19 '18 at 15:15









                    Kristjan KicaKristjan Kica

                    2,2071926




                    2,2071926























                        1














                        Let's say, a has n elements and b has m. Then the first iteration over a will have a complexity of O(n) because it will be done n times in the worst case.



                        Inside that loop, there are two iterations over b, which are O(m) each and since they are done after another, their complexity is summed up to O(m) + O(m) = O(m + m) = O(m).



                        So the entire complexity computes like this:



                        O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m)



                        If the lengths of a and b are equal, both will have a complexity of O(n) making it =(n*n) = O(n^2).



                        To finally answer your question: No, you have not achieved a linear complexity of O(n) with your code.






                        share|improve this answer






























                          1














                          Let's say, a has n elements and b has m. Then the first iteration over a will have a complexity of O(n) because it will be done n times in the worst case.



                          Inside that loop, there are two iterations over b, which are O(m) each and since they are done after another, their complexity is summed up to O(m) + O(m) = O(m + m) = O(m).



                          So the entire complexity computes like this:



                          O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m)



                          If the lengths of a and b are equal, both will have a complexity of O(n) making it =(n*n) = O(n^2).



                          To finally answer your question: No, you have not achieved a linear complexity of O(n) with your code.






                          share|improve this answer




























                            1












                            1








                            1







                            Let's say, a has n elements and b has m. Then the first iteration over a will have a complexity of O(n) because it will be done n times in the worst case.



                            Inside that loop, there are two iterations over b, which are O(m) each and since they are done after another, their complexity is summed up to O(m) + O(m) = O(m + m) = O(m).



                            So the entire complexity computes like this:



                            O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m)



                            If the lengths of a and b are equal, both will have a complexity of O(n) making it =(n*n) = O(n^2).



                            To finally answer your question: No, you have not achieved a linear complexity of O(n) with your code.






                            share|improve this answer















                            Let's say, a has n elements and b has m. Then the first iteration over a will have a complexity of O(n) because it will be done n times in the worst case.



                            Inside that loop, there are two iterations over b, which are O(m) each and since they are done after another, their complexity is summed up to O(m) + O(m) = O(m + m) = O(m).



                            So the entire complexity computes like this:



                            O(n) * (O(m) + O(m)) = O(n) * O(m) = O(n * m)



                            If the lengths of a and b are equal, both will have a complexity of O(n) making it =(n*n) = O(n^2).



                            To finally answer your question: No, you have not achieved a linear complexity of O(n) with your code.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 19 '18 at 15:23

























                            answered Nov 19 '18 at 15:18









                            deHaardeHaar

                            2,45251628




                            2,45251628






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377418%2fhave-i-achieved-linear-time-complexity-on-for-this-array-comparison-algorithm%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Xamarin.form Move up view when keyboard appear

                                Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                Anylogic : not able to use stopDelay()