Algorithm
Алгоритм
An algorithm is a precise procedure for solving a problem. For example, you can find a value in a list by checking each item until you find a match or reach the end.
What is an algorithm?
An algorithm tells you how to get from a problem's input to its result. Suppose you need to find a name in a contact list. You could start at the top and check each name, or, if the names are in alphabetical order, check the middle and rule out half the list at a time. Both approaches solve a search problem, but they use different rules and make different assumptions about the input.
An algorithm is the procedure, not the source code that implements it. You can describe it in pseudocode, implement it in Python or Go, or trace it on paper. A program can combine several algorithms, such as sorting a list and then searching it.
Specify the result before writing the steps
For a search, does the caller want a yes-or-no answer, the first matching position, or every matching position? What should happen when nothing matches? The answers shape the algorithm. A correct procedure must stop and produce the specified result for every valid input, not just the examples you tried.
Example: finding the first match
def first_match(items, target):
for index, value in enumerate(items):
if value == target:
return index
return None
This is linear search. With [8, 3, 3] and target 3, it returns 1: Python counts from zero, and the scan stops as soon as it finds a match. An empty list returns None, just like any other list with no match. If the target is absent or appears only at the end, the procedure checks all n items. Assuming each comparison takes constant time, that gives O(n) worst-case time and O(1) extra space.
Choosing an algorithm in practice
Algorithms handle tasks such as ranking results, finding routes, and processing records. The right choice depends on how the data is stored, how often it changes, and how many times you need to run the operation. Sorting an unsorted array just to run one binary search usually costs more than scanning it once. For repeated lookups on a rarely changing array, the upfront sorting cost may be worthwhile.
Big O describes how resource use grows as the input gets larger. It does not predict elapsed time. A simple scan can beat a more elaborate method on a small input even if the other method scales better.
What interviewers look for
Before coding, state what the inputs and outputs are and ask about assumptions that affect your approach. Explain a straightforward solution, why it returns the right result, and how much time and extra space it needs. Walk through a small example and an edge case, then discuss what would make a different algorithm worth using.