Algorithms Conventions
Introduction
There are some common conventions within algorithms coding that make it easier to read, memorize, and understand algorithms if you know them. Things like why are we returning -1
if an algorithm fails?
Common Variables
left
/right
& start
/end
& low
/high
In algorithms, the terms left/right, start/end, and low/high are often used interchangeably to represent the boundaries of a search space or a range of elements. Example:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
The while (left <= right)
loop condition ensures that there is a valid search space to look for the target. For example if left = 3
and right = undefined
, the loop will exit immediately as there is no valid search space.
mid
The mid
variable is commonly used in binary search algorithms to represent the middle index of the search space. It is calculated as the average of left
and right
indices.
start
/end
In problems involving intervals or ranges, start
and end
are often used to represent the beginning and end of a range. These variables help define the boundaries of the interval being processed.
Returning -1
for Element Not Found
Returning -1
when a target element is not found in a search algorithm is a common practice for several reasons:
Historical Precedent: Early programming languages and libraries, such as C and the Unix standard library, established the convention of returning -1
to indicate failure or "not found" because it was a straightforward and efficient way to signal an error condition or absence. This convention has carried over into many modern languages and APIs.
Index Semantics: In the context of array or list searches, the result typically represents an index position. Valid indices range from 0
to n-1
(where n
is the length of the array). Since -1
is not a valid index, it clearly indicates that the element is not present without overlapping with any potential valid index values.
Simplicity and Efficiency: Using -1
as a sentinel value for "not found" is simple and does not require additional type checking or memory overhead compared to returning null or false. It integrates seamlessly with arithmetic operations and comparisons.
Uniformity Across Languages: Many languages, libraries, and frameworks have adopted -1
as a convention, leading to uniformity in coding practices. This makes code more predictable and consistent across different environments and languages.
Compatibility: Using -1
maintains compatibility with older codebases and libraries that follow this convention. Changing the return value to null or false might require additional checks and updates in existing code, introducing complexity and potential for bugs.
Common Single-Letter Variables
In many coding problems, especially in competitive programming and platforms like LeetCode, certain single-letter variables are commonly used. Here's a list of these variables and their typical uses:
Loop Variables: i, j, k
Usage: Index in loops, especially for arrays and lists. Example: for (let i = 0; i < n; i++) { ... }
While k
can be used as a third index in nested loops, it is often used in three-dimensional problems.
Sizes and Counts: n, m
Usage: Size of an array, number of elements, or problem-specific variable (e.g., length of a string).
Example: const n = arr.length;
Coordinates and Geometry: x, y, r
Usage: General-purpose variable, often used in mathematical contexts or coordinates.
Example: let x = 5;
It is common for r
to represent the radius in geometry problems.
Graph-related: u, v, w
u
Usage: Vertex in graph problems, or general-purpose variable.
Example: let u = graph[i];
v
Usage: Vertex in graph problems, or general-purpose variable.
Example: let v = graph[i];
w
Usage: Weight in graph problems, or general-purpose variable.
Example: let w = graph[i];
String and Character: c, s
c
Usage: Character in string problems, or general-purpose variable.
Example: let c = str[i];
s
Usage: String, sum, or stack.
Example: let s = "hello"; or let s = new Stack();
Data Structures: s (stack), q (queue), p (pointer)
s
Usage: Stack in data structure problems.
Example: let s = new Stack();
q
Usage: Queue in data structure problems.
Example: let q = new Queue();
p
Usage: Pointer in linked list problems.
Example: let p = head;
General-purpose: a, b, t, z
a
Usage:General purpose variable often paired with b
, or used to represent an array.
Example: let a = [1, 2, 3];
t
Usage: Target in search problems, temporary variable, or tree node.
Example: let t = targetValue;
or let t = root;
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.