Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Dynamic time warping

Dynamic Time Warping (DTW) is an algorithm to measure similarity between two time series that may be stretched or compressed in time, by finding an optimal alignment (warping) minimizing cumulative distance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Dynamic Time Warping is used by engineers when comparing sequences (time series) that are similar but not aligned in time. Examples: speech signals spoken at different speeds, gesture or activity sensor data with different durations, and template matching where the same event is stretched or compressed. DTW gives a flexible, robust distance measure for nearest-neighbour classifiers, template matching and clustering of time series.

Key ideas

  • Cost matrix: For sequences x (length n) and y (length m), the cost matrix is the n-by-m matrix whose (i,j) entry is the local distance d(xi,yj). Draw an n×m grid, label rows i = 1..n on the vertical axis and columns j = 1..m on the horizontal axis.

  • Warping path: A warping path is a sequence of grid points p = (p1, p2, ..., pL) where each pk = (i_k, j_k) is a pair of indices with 1 ≤ i_1 ≤ ... ≤ i_L = n and 1 ≤ j_1 ≤ ... ≤ j_L = m, satisfying three constraints:

    • Boundary: p1 = (1,1) and pL = (n,m).
    • Monotonicity: i_k ≤ i_{k+1} and j_k ≤ j_{k+1} (time order preserved).
    • Step-size (continuity): Allowed moves are (1,0), (0,1), (1,1) between consecutive path points (never skip indices). These ensure a continuous, monotone mapping between the two sequences. (Defined here; draw path in the cost matrix from top-left to bottom-right.)
  • Cumulative cost of a warping path: The cost of a warping path p is the sum of local distances along the path: sum_{k=1..L} d(x_{i_k}, y_{j_k}). The DTW distance is the minimum cumulative cost over all valid warping paths. (Definition and optimization target.)

  • Dynamic programming recurrence (exact statement): Let D(i,j) be the minimum cumulative cost to align prefixes x1..xi and y1..yj, ending at (i,j). Then, assuming D(0,0)=0 and D(i,0)=D(0,j)=+infinity for i>0 or j>0, the recurrence is: D(i,j) = d(xi,yj) + min{ D(i-1,j), D(i,j-1), D(i-1,j-1) }. The DTW cost is D(n,m). The assumptions: sequences are discrete, local costs non-negative. (Derivation below.)

  • Derivation of recurrence (step-by-step):

    1. D(i,j) is the minimal cost among warping paths that end at cell (i,j).
    2. Any path to (i,j) must come from one of the three predecessor cells: (i-1,j), (i,j-1), or (i-1,j-1) because of the allowed steps.
    3. The minimal cost to reach (i,j) is therefore the local cost d(xi,yj) plus the minimal of the three predecessor costs. This leads to the recurrence above.
  • Normalization (optional): Many uses divide D(n,m) by path length L to compensate for different lengths of the optimal path, producing an average per-step cost. This is not part of the basic DTW definition but is common in practice.

  • Constraints to reduce warping: To avoid pathological alignments, practitioners use global constraints like the Sakoe–Chiba band (limit |i - j| ≤ r for a fixed radius r) or the Itakura parallelogram. These restrict feasible (i,j) pairs to a band around the diagonal. (State and draw band or parallelogram on the grid.) For unequal lengths (n ≠ m), center the band on the line j ≈ i·m/n rather than the main diagonal.

  • Complexity: The naive dynamic programming computes all D(i,j) for i=1..n, j=1..m, so time complexity is O(n·m) and memory O(n·m). Space can be reduced to O(min(n,m)) if only the final cost is needed (keep only two rows/columns), and to O(n·r) under a Sakoe–Chiba band. With band constraints, time complexity reduces to O(n·r) when r ≪ m. In similarity search, early abandoning and lower bounds such as LB_Keogh enable pruning.

  • Metric properties: DTW distance is non-negative and symmetric (if local distance is symmetric) and D(x,x)=0. However DTW generally does not satisfy the triangle inequality, therefore is not a metric in the strict sense. (A small counterexample appears in Worked examples.)

  • Diagram to draw for an exam answer: Draw a rectangular grid with i along vertical axis from 1 at top to n at bottom, j along horizontal axis from 1 at left to m at right. Shade some cells to show a Sakoe–Chiba band around diagonal. Draw a path from (1,1) to (n,m) using steps down, right, or diagonal. Label a few cells with their local distances and show one path summing those values to give its cost.

Formulas

d(x_i, y_j) = |x_i - y_j| — local absolute distance; x_i, y_j are real numbers; unit = units of the sequence (e.g., volts, meters) or unitless; applies for scalar sequences.

d(x_i, y_j) = (x_i - y_j)^2 — local squared distance; units = (units of x)^2; used when penalising large errors more.

D(i,j) = d(x_i, y_j) + min( D(i-1,j), D(i,j-1), D(i-1,j-1) ) — cumulative cost recurrence; D(0,0)=0, D(i,0)=D(0,j)=+∞ for i>0 or j>0; units = same as d.

DTW(x,y) = D(n,m) — final DTW cost for sequences x of length n and y of length m; units = same as d or normalized if divided by path length.

Normalized DTW = D(n,m) / L — where L is the length of the optimal warping path; unit = same as d.

Time and space complexity: O(n·m) time and O(n·m) space (or O(min(n,m)) space if only the final cost is needed) — n and m are lengths of the two sequences; applies when evaluating the whole cost matrix.

If using a Sakoe–Chiba band of radius r: O(n·r) time and O(n·r) space complexity (assuming n ≈ m and r ≪ n).

Worked examples

Example 1 — manual numeric DTW (small sequences) Given sequences x = (1, 3, 4) and y = (1, 2, 3, 4). Use local distance d(a,b)=|a-b|. Step 1: build cost matrix (rows i=1..3, cols j=1..4):

  • d(1,1)=0, d(1,2)=1, d(1,3)=2, d(1,4)=3
  • d(3,1)=2, d(3,2)=1, d(3,3)=0, d(3,4)=1
  • d(4,1)=3, d(4,2)=2, d(4,3)=1, d(4,4)=0 Step 2: compute D(i,j) with D(0,0)=0 and D(i,0)=D(0,j)=∞:
  • D(1,1)=0 + min(∞,∞,0) = 0
  • D(1,2)=1 + min(∞,0,∞) = 1
  • D(1,3)=2 + min(∞,1,∞) = 3
  • D(1,4)=3 + min(∞,3,∞) = 6
  • D(2,1)=2 + min(0,∞,∞) = 2
  • D(2,2)=1 + min(1,2,0) = 1
  • D(2,3)=0 + min(3,1,1) = 1
  • D(2,4)=1 + min(6,1,3) = 2
  • D(3,1)=3 + min(2,∞,∞) = 5
  • D(3,2)=2 + min(1,5,2) = 3
  • D(3,3)=1 + min(1,3,1) = 2
  • D(3,4)=0 + min(2,2,1) = 1 Step 3: DTW cost = D(3,4) = 1 (units of the sequence). The optimal path can be traced backward: (3,4) ← (2,3) ← (2,2) ← (1,1). So alignment maps x1→y1, x2→y2,y3, x3→y4. Final answer: DTW(x,y)=1.

Example 2 — Python code (computes DTW and prints cost and path)

# Simple DTW dynamic programming implementation
import math

def dtw(x, y, dist=lambda a,b: abs(a-b)):
    n, m = len(x), len(y)
    # initialize
    D = [[math.inf] * (m+1) for _ in range(n+1)]
    D[0][0] = 0
    for i in range(1, n+1):
        for j in range(1, m+1):
            cost = dist(x[i-1], y[j-1])
            D[i][j] = cost + min(D[i-1][j], D[i][j-1], D[i-1][j-1])
    # traceback path
    i, j = n, m
    path = []
    while i>0 and j>0:
        path.append((i, j))
        prev = min((D[i-1][j], (i-1,j)), (D[i][j-1], (i,j-1)), (D[i-1][j-1], (i-1,j-1)), key=lambda t: t[0])
        (i,j) = prev[1]
    path.reverse()
    return D[n][m], path

if __name__ == '__main__':
    x = [1,3,4]
    y = [1,2,3,4]
    cost, path = dtw(x,y)
    print('Cost:', cost)
    print('Path:', path)

Sample input: the sequences are hard-coded in the program above. Exact output when run: Cost: 1 Path: [(1, 1), (2, 2), (2, 3), (3, 4)]

Example 3 — DTW is not a metric (triangle inequality counterexample) Let a = (0,0,0,0), b = (0,1), c = (1,1,1,1). Using absolute local distance and unnormalized DTW:

  • DTW(a,b) = 1 (align three 0s with b1=0 at cost 0 and the last 0 with b2=1 at cost 1; dynamic programming gives D(4,2)=1).
  • DTW(b,c) = 1 (align three 1s with b2=1 at cost 0 and align one 1 with b1=0 at cost 1; dynamic programming gives D(2,4)=1).
  • DTW(a,c) = 4 (all pairings incur |0−1|=1; dynamic programming gives D(4,4)=4). Thus DTW(a,c) = 4 > DTW(a,b) + DTW(b,c) = 2, violating the triangle inequality. This shows DTW is not a metric.

Common mistakes

  • Mixing up axes when drawing the cost matrix (label i on rows and j on columns clearly).
  • Not applying monotonicity/continuity constraints — allowing illegal steps that skip indices.
  • Using unnormalized DTW without noting path length when comparing many pairs; long paths tend to produce larger sums.
  • Claiming DTW is a metric without noting triangle inequality can fail.
  • Forgetting to limit band radius r when claiming reduced complexity; complexity only reduces if band size << n·m.

For your exam

Question types you will see:

  • Definitions: define warping path, cost matrix, local distance, and state recurrence. Full-marks answer: clear definitions with constraints (boundary, monotonicity, step-size) and a short diagram.
  • Derivation: derive the DP recurrence for D(i,j). Full-marks answer: show decomposition of optimal path ending at (i,j) into predecessor plus local cost and write recurrence and base cases.
  • Numerical: compute DTW for small sequences by hand. Full-marks answer: show cost matrix, step-by-step D(i,j) table, trace optimal path and give final cost with units.
  • Algorithm/program: write a DP algorithm or pseudocode and state complexity. Full-marks answer: correct pseudocode, boundary conditions, complexity O(n·m), and mention band constraints.
  • Discussion/short note: pros/cons of DTW and practical constraints (Sakoe–Chiba, Itakura). Full-marks: discuss flexibility vs over-warping, complexity, and mention non-metric property.

Quick check

  1. State the three allowed moves in a warping path.
  2. Write the DP recurrence for D(i,j).
  3. What is the time complexity of DTW for sequences of lengths n and m? Answers: 1) (1,0), (0,1), (1,1). 2) D(i,j)=d(x_i,y_j)+min(D(i-1,j),D(i,j-1),D(i-1,j-1)). 3) O(n·m).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?