WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Data Structures & Algorithms Β· Basic Β· question 13 of 100

What is the time complexity of a linear search algorithm?

πŸ“• Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers β€” PDF + EPUB for $5

The time complexity of a linear search algorithm is O(n), where n is the number of elements in the list or array being searched. This means that the worst-case time complexity of a linear search algorithm grows linearly with the size of the input.

In a linear search algorithm, we start at the first element of the list or array and compare it with the target value we are searching for. If the value matches, we return its index. If not, we move on to the next element and repeat the process until we find the target value or reach the end of the list or array.

Here is an example of a linear search algorithm in Java:

public static int linearSearch(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}

In this example, we pass in an integer array arr and a target value target. The algorithm iterates through each element of the array and checks if it matches the target value. If a match is found, the index of the element is returned. If no match is found, the function returns -1.

The worst-case time complexity of this algorithm is O(n), because in the worst case scenario, we will need to iterate through all n elements of the array before finding the target value or determining that it does not exist in the array.

In summary, the time complexity of a linear search algorithm is O(n), which means that its worst-case time complexity grows linearly with the size of the input. This algorithm is not efficient for large datasets, but it is simple and easy to implement for small datasets or when the elements are unsorted.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Data Structures & Algorithms interview β€” then scores it.
πŸ“ž Practice Data Structures & Algorithms β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers β€” PDF + EPUB for $5

All 100 Data Structures & Algorithms questions Β· All topics