Linear Search

Linear Search

DSA Notes

  1. There are two ways to search an array for linear search.

    i. Access each element using for loop

    ii. Array indexing

  2. Time complexity-

    i. Best case- O(1) if element found on first index.

    ii. Worst case- O(n) element might be found on the last/ nth index.

  3. Time complexity is how my time grows with my input size.

  4. Before solving question directing via coding, write down steps form diff logic that can be used to solve problem. Try to use functions for each operation/steps involved in solving the problem.

  5. Example- arr = {22, 1, 0, 121} Find even no digits in array.

    steps-

    i. find no of elements in each digit

    ii. find each digit is even or not

    iii If even increase count++ and return it

  6. There are 3 ways to count the number of digits-

    i. N/10 remove last digit (do count++)

    ii. convert digit into string, do .length

    iii Optimized - Math.log10(num)+1

  7. Another example- Find max sum among each row in 2D array:

    i. First for loop- traverse for each rows (till rows.length, all rows)

    ii. Second for loop- traverse for each element of column of ith row. i.e- rows(i).length

  8. if need to take row sum, variable for multiplication for each rows- declare variable after first for loop.