⚡ TL;DR
Print the absolute difference matrix pattern in Go with working code and output. Working implementation, sample run, and complexity analysis included.
The Absolute Difference Matrix pattern is a classic loop exercise. Here’s the complete implementation in Go with working code and output.
Pattern to Print
1 2 3 4 5
2 1 2 3 4
3 2 1 2 3
4 3 2 1 2
5 4 3 2 1Implementation
package main
import (
"fmt"
"strings"
)
func main() {
n := 5
for i := 0; i < n; i++ {
var row []string
for j := 0; j < n; j++ {
d := i - j
if d < 0 {
d = -d
}
row = append(row, fmt.Sprint(d+1))
}
fmt.Println(strings.Join(row, " "))
}
}Output
1 2 3 4 5
2 1 2 3 4
3 2 1 2 3
4 3 2 1 2
5 4 3 2 1How It Works
Each cell holds |row − column| + 1. The main diagonal is all 1s, values grow toward the edges, and the whole matrix is symmetric across that diagonal — a one-line abs() call drives the entire shape.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(n²) — the grid is stored before printing
FAQ
How do you print the Absolute Difference Matrix pattern in Go?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Go implementation with expected output is shown in the sections above.
What is the time complexity of the Absolute Difference Matrix pattern in Go?
The time complexity is O(n²) and the space complexity is O(n²), since the pattern is built on a grid that is filled first and then printed row by row.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →