Number Pattern Problems

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/168 Known filtered set
Difficulty
Read Full Guide Question: 1 of 168

Java Logic Development · Chapter 07 Companion Article

Number Pattern Problems

Fourteen number patterns — counters, triangles, Pascal's and palindromic pyramids, binary grids, a diamond, concentric layers, a snake, and a spiral — each solved by connecting row, column, and value instead of memorizing output.

Overview

Number pattern problems are useful for developing control over nested loops, row-column relationships, counters, arithmetic conditions, matrix traversal, and mathematical logic.

Most number patterns can be solved by answering three questions:

  1. How many rows are required?
  2. How many values should appear in each row?
  3. What determines the value printed at each row and column?

The outer loop normally controls rows. The inner loop controls columns or values printed inside each row.

1. Sequential Number Pattern

Problem

Print numbers continuously from left to right across multiple rows. For n = 4:

Example
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Core Logic

A separate counter is required because the printed number depends on the total number of values already printed, not directly on the current row or column. Start number from 1 and increment it after every print operation.

Java Program

Java
public class SequentialNumberPattern {
    public static void main(String[] args) {
        int n = 4;
        int number = 1;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= n; col++) {
                System.out.print(number + " ");
                number++;
            }
            System.out.println();
        }
    }
}

Output

Output
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Why It Works

The nested loops generate n × n positions. The number variable advances independently after each position, producing one continuous sequence.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Resetting number inside the outer loop causes every row to restart from 1.

Interview Tip

A sequential value does not always require a separate counter. The value at (row, col) can also be calculated using (row - 1) * n + col.

2. Repeated Number Pattern

Problem

Print the current row number repeatedly in that row. For n = 5:

Example
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Core Logic

The row number itself is the value to print. Row r contains exactly r values.

Java Program

Java
public class RepeatedNumberPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(row + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Why It Works

The inner loop executes row times. Because row is printed on each iteration, the number and repetition count increase together.

Complexity

  • Time: O(n²)
  • Space: O(1)

Important Observation

The actual number of print operations is 1 + 2 + 3 + ... + n, which equals n(n + 1) / 2.

3. Increasing Number Triangle

Problem

Print numbers from 1 up to the current row number. For n = 5:

Example
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Core Logic

The column position determines the value. For every row, printed value = col.

Java Program

Java
public class IncreasingNumberTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(col + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Why It Works

Each row contains as many columns as its row number. Since col starts from 1, every row naturally produces 1 through row.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Printing row instead of col changes the pattern into a repeated-number triangle.

4. Decreasing Number Triangle

Problem

Start with n values and reduce the number of printed values after every row. For n = 5:

Example
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Core Logic

For row r, the number of columns is n - row + 1. The column number itself is printed.

Java Program

Java
public class DecreasingNumberTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= n - row + 1; col++) {
                System.out.print(col + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Why It Works

As row increases, n - row + 1 decreases. Therefore, every new row contains one fewer value.

Complexity

  • Time: O(n²)
  • Space: O(1)

5. Reverse Number Triangle

Problem

Print numbers in descending order within every row. For n = 5:

Example
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1

Core Logic

The inner loop begins from the current row number and moves backward to 1.

Java Program

Java
public class ReverseNumberTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int number = row; number >= 1; number--) {
                System.out.print(number + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1

Why It Works

Row r starts from r, and the inner variable decreases until it reaches 1.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Variation

You may be asked to print:

Example
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

That variation requires changing both the starting value and row length.

6. Floyd's Triangle

Problem

Print consecutive natural numbers in triangular form. For n = 5:

Example
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Core Logic

Maintain one counter across all rows. Row r contains r numbers.

Java Program

Java
public class FloydTriangle {
    public static void main(String[] args) {
        int n = 5;
        int number = 1;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(number + " ");
                number++;
            }
            System.out.println();
        }
    }
}

Output

Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Dry Run

For n = 3:

  • Row 1 prints 1
  • Counter becomes 2
  • Row 2 prints 2 3
  • Counter becomes 4
  • Row 3 prints 4 5 6

Complexity

  • Time: O(n²)
  • Space: O(1)

Useful Formula

The final number printed after n rows is n(n + 1) / 2.

7. Pascal's Triangle

Problem

Print Pascal's Triangle. For n = 5:

Example
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Mathematical Property

Each interior number is the sum of the two values above it. Pascal's Triangle is also based on binomial coefficients: C(row, col). Instead of repeatedly calculating factorials, the next value in a row can be derived from the previous value.

Efficient Relationship

If the current value is value, the next one is value = value * (row - col) / col when rows are treated using zero-based mathematical indexing.

Java Program

Java
public class PascalTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 0; row < n; row++) {
            int value = 1;
            for (int col = 0; col <= row; col++) {
                System.out.print(value + " ");
                value = value * (row - col) / (col + 1);
            }
            System.out.println();
        }
    }
}

Output

Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Why It Works

The first value of every row is always 1. Every later value is calculated from the previous binomial coefficient. This avoids separate factorial calculations.

Complexity

  • Time: O(n²)
  • Auxiliary Space: O(1)

Edge Case

For large row numbers, int can overflow. Use long or BigInteger when larger coefficients are required.

Interview Tip

Generating Pascal's Triangle through factorial calculations is valid but unnecessarily expensive and more vulnerable to overflow.

8. Palindromic Number Pyramid

Problem

Create a centered pyramid whose rows read the same forward and backward. For n = 5:

Example
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5

Core Logic

Each row has three parts:

  1. Leading spaces
  2. Decreasing numbers from row to 1
  3. Increasing numbers from 2 to row

Java Program

Java
public class PalindromicNumberPyramid {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int space = 1; space <= n - row; space++) {
                System.out.print("  ");
            }
            for (int number = row; number >= 1; number--) {
                System.out.print(number + " ");
            }
            for (int number = 2; number <= row; number++) {
                System.out.print(number + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
        1
      2 1 2
    3 2 1 2 3
  4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5

Why It Works

The value 1 forms the center of every row. The decreasing sequence creates the left half, while the increasing sequence mirrors it on the right.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Starting the second number loop from 1 prints the center value twice.

9. Binary Number Pattern

Problem

Print alternating 0 and 1 values across rows and columns. For n = 5:

Example
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0

Core Logic

The value depends on whether row + col is even or odd. Using zero-based indexes: value = (row + col) % 2.

Java Program

Java
public class BinaryNumberPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                System.out.print((row + col) % 2 + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0

Why It Works

Moving one position horizontally or vertically changes the parity of row + col, so the value alternates automatically.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Insight

Parity expressions such as (row + col) % 2 are often more useful than manually switching a boolean or integer variable.

10. 0-1 Triangle Pattern

Problem

Print a triangular alternating binary pattern. For n = 5:

Example
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

Core Logic

Using one-based row and column numbers, (row + col) % 2 == 0 prints 1; otherwise it prints 0.

Java Program

Java
public class ZeroOneTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= row; col++) {
                int value = (row + col) % 2 == 0 ? 1 : 0;
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

Why It Works

Positions with an even row + col receive 1, while positions with an odd sum receive 0.

Complexity

  • Time: O(n²)
  • Space: O(1)

Difference from Binary Square Pattern

The binary square contains exactly n columns in every row. The 0-1 triangle contains only row columns.

11. Number Diamond Pattern

Problem

Create a diamond using repeated row numbers. For n = 4:

Example
1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
3 3 3 3 3
2 2 2
1

Pattern Structure

For row r in the upper half, values = 2 * r - 1. The lower half performs the same logic in reverse.

Java Program

Java
public class NumberDiamondPattern {
    public static void main(String[] args) {
        int n = 4;
        for (int row = 1; row <= n; row++) {
            for (int space = 1; space <= n - row; space++) {
                System.out.print("  ");
            }
            for (int col = 1; col <= 2 * row - 1; col++) {
                System.out.print(row + " ");
            }
            System.out.println();
        }
        for (int row = n - 1; row >= 1; row--) {
            for (int space = 1; space <= n - row; space++) {
                System.out.print("  ");
            }
            for (int col = 1; col <= 2 * row - 1; col++) {
                System.out.print(row + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
      1
    2 2 2
  3 3 3 3 3
4 4 4 4 4 4 4
  3 3 3 3 3
    2 2 2
      1

Why It Works

The upper half increases the number of elements by two per row. The lower half reverses the process.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Starting the lower half from n prints the widest row twice.

12. Concentric Number Pattern

Problem

Print numbers in nested rectangular layers. For n = 4:

Example
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4

Pattern Size

For input n, the matrix dimension is 2 * n - 1. For n = 4, size = 7.

Core Idea

The value depends on the cell's minimum distance from any edge. For coordinates (row, col), calculate:

Text
top = row
left = col
bottom = size - 1 - row
right = size - 1 - col

The minimum of these distances identifies the current layer. Then value = n - minimumDistance.

Java Program

Java
public class ConcentricNumberPattern {
    public static void main(String[] args) {
        int n = 4;
        int size = 2 * n - 1;
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                int top = row;
                int left = col;
                int bottom = size - 1 - row;
                int right = size - 1 - col;
                int distance = Math.min(Math.min(top, bottom), Math.min(left, right));
                System.out.print((n - distance) + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4

Why It Works

All cells equally distant from the nearest border belong to the same layer. The outer layer has distance 0, the next layer distance 1, and so on.

Complexity

Since the matrix size is approximately 2n × 2n:

  • Time: O(n²)
  • Space: O(1)

Interview Value

This pattern is more useful than simple triangle patterns because it tests matrix-coordinate reasoning instead of only nested-loop repetition.

13. Snake Number Pattern

Problem

Print sequential numbers from left to right on one row and right to left on the next. For n = 4:

Example
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

Core Logic

Odd-numbered rows move left to right. Even-numbered rows represent the same sequence in reverse. Instead of creating an array, calculate the value directly. For odd rows: value = (row - 1) * n + col. For even rows: value = row * n - col + 1.

Java Program

Java
public class SnakeNumberPattern {
    public static void main(String[] args) {
        int n = 4;
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= n; col++) {
                int value;
                if (row % 2 != 0) {
                    value = (row - 1) * n + col;
                } else {
                    value = row * n - col + 1;
                }
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

Dry Run

For row 2, n = 4. At column 1:

Text
value = 2 * 4 - 1 + 1
value = 8

At column 4:

Text
value = 2 * 4 - 4 + 1
value = 5

So row 2 becomes 8 7 6 5.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Tip

A snake pattern is closely related to zigzag matrix traversal. The same technique appears when traversing two-dimensional arrays.

14. Spiral Number Pattern

Problem

Fill a matrix with sequential numbers in clockwise spiral order. For n = 4:

Example
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

Why This Pattern Is Different

Simple patterns usually print values immediately. A spiral pattern is easier to solve by first filling a two-dimensional array because movement changes direction repeatedly. Four boundaries are maintained: top, bottom, left, and right.

Spiral Traversal Order

Each cycle performs:

  1. Left to right across the top
  2. Top to bottom along the right
  3. Right to left across the bottom
  4. Bottom to top along the left

After each traversal, the corresponding boundary moves inward.

Java Program

Java
public class SpiralNumberPattern {
    public static void main(String[] args) {
        int n = 4;
        int[][] matrix = new int[n][n];
        int top = 0;
        int bottom = n - 1;
        int left = 0;
        int right = n - 1;
        int number = 1;
        while (top <= bottom && left <= right) {
            for (int col = left; col <= right; col++) {
                matrix[top][col] = number++;
            }
            top++;
            for (int row = top; row <= bottom; row++) {
                matrix[row][right] = number++;
            }
            right--;
            if (top <= bottom) {
                for (int col = right; col >= left; col--) {
                    matrix[bottom][col] = number++;
                }
                bottom--;
            }
            if (left <= right) {
                for (int row = bottom; row >= top; row--) {
                    matrix[row][left] = number++;
                }
                left++;
            }
        }
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                System.out.print(matrix[row][col] + " ");
            }
            System.out.println();
        }
    }
}

Output

Output
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

Boundary Dry Run

Initially:

Text
top = 0
bottom = 3
left = 0
right = 3

First traversal fills 1 2 3 4. Then the right edge receives:

Text
5
6
7

The bottom edge is filled backward: 10 9 8 7. The left edge is filled upward:

Text
12
11
10

The boundaries then move inward and the same process fills:

Text
13 14
16 15

Why Boundary Checks Matter

After reducing top, bottom, left, or right, some boundaries can cross. Without checks such as if (top <= bottom), a row or column may be processed twice for certain matrix sizes.

Complexity

  • Filling Matrix: O(n²)
  • Printing Matrix: O(n²)
  • Total Time: O(n²)
  • Space: O(n²)

Interview Tip

Spiral traversal is an important matrix problem. Interviewers may ask variations such as:

  • Spiral traversal of an existing matrix
  • Anti-clockwise spiral
  • Spiral starting from the center
  • Rectangular matrix spiral traversal
  • Returning values in a list instead of printing them

Number Pattern Logic Comparison

PatternMain Logic ConceptExtra Storage
Sequential NumberGlobal counterO(1)
Repeated NumberRow-controlled valueO(1)
Increasing TriangleColumn-controlled valueO(1)
Decreasing TriangleDecreasing row widthO(1)
Reverse TriangleReverse inner loopO(1)
Floyd's TriangleContinuous counterO(1)
Pascal's TriangleBinomial coefficientO(1)
Palindromic PyramidMirror sequenceO(1)
Binary PatternRow-column parityO(1)
0-1 TrianglePosition parityO(1)
Number DiamondUpper/lower symmetryO(1)
Concentric PatternDistance from boundaryO(1)
Snake PatternRow parityO(1)
Spiral PatternMatrix boundariesO(n²)

How to Solve Number Pattern Problems

1. Identify the Row Structure

First determine whether the pattern has:

  • Fixed row width
  • Increasing width
  • Decreasing width
  • Symmetrical upper and lower halves
  • A complete matrix

For example:

Example
1
1 2
1 2 3

has increasing width, so the inner-loop condition naturally becomes col <= row.

2. Find the Relationship Between Position and Value

Check whether the printed value depends on:

  • row
  • col
  • row + col
  • A running counter
  • Distance from an edge
  • Previous values

Examples: repeated pattern uses value = row, increasing triangle uses value = col, binary pattern uses value = (row + col) % 2.

3. Separate Shape Logic from Value Logic

Pattern problems normally contain two independent decisions. Shape logic: should something be printed at this position? Value logic: what should be printed? This distinction becomes particularly useful for pyramids, diamonds, hollow patterns, and matrices.

4. Use a Counter Only When Necessary

A counter is useful when values must continue across rows:

Example
1
2 3
4 5 6

But a counter is unnecessary when the value can be calculated directly from row and column positions. For example, in an n × n sequential matrix, value = row * n + col + 1 when using zero-based indexes.

5. Recognize Symmetry

Patterns such as diamonds and palindromic pyramids are usually easier when divided into independent halves. For a diamond:

  • Build the upper half
  • Build the lower half in reverse
  • Avoid printing the middle row twice

Important Nested Loop Concepts

Outer Loop

Usually controls the number of rows. Example: for (int row = 1; row <= n; row++).

Inner Loop

Usually controls numbers, columns, spaces, or repeated values. Example: for (int col = 1; col <= row; col++).

Multiple Inner Loops

Complex patterns may require separate loops for leading spaces, left-side values, and right-side values. For example, a palindromic pyramid uses all three.

Row and Column Formulas Worth Remembering

For an n × n matrix with one-based indexes:

FormulaExpression
Sequential value(row - 1) * n + col
Snake odd row(row - 1) * n + col
Snake even rowrow * n - col + 1
Binary alternating position(row + col) % 2
Triangle values in row rr
Diamond width at row r2 * r - 1
Concentric matrix size2 * n - 1

These formulas are more important than memorizing complete programs.

Common Number Pattern Mistakes

Incorrect Inner Loop Limit

Using col <= n instead of col <= row changes a triangle into a rectangle.

Resetting a Continuous Counter

For Floyd's Triangle, this is incorrect:

Java
for (int row = 1; row <= n; row++) {
    int number = 1;
    // ...
}

The counter would restart for each row. Declare it before the outer loop.

Printing the Middle Element Twice

In a palindromic pattern, 3 2 1 1 2 3 is not the intended palindrome when the desired center is one 1. Start the second loop from 2, not 1.

Duplicating the Middle Diamond Row

If the top half ends at n, the bottom half should normally begin at n - 1.

Mixing Zero-Based and One-Based Indexes

Expressions such as (row + col) % 2 can produce a reversed binary pattern depending on whether the loops begin from 0 or 1. Use one indexing convention consistently.

Ignoring Integer Overflow

Pascal's Triangle values increase rapidly. Using int is suitable only for relatively small rows. Larger calculations may require long or BigInteger.

Pattern Printing Without Extra Arrays

Most patterns in this chapter should be generated directly using loop variables and formulas. Examples include:

  • Sequential patterns
  • Number triangles
  • Floyd's Triangle
  • Binary patterns
  • Diamonds
  • Concentric patterns
  • Snake patterns

Direct generation usually provides:

  • O(1) auxiliary space
  • Simpler logic
  • Less unnecessary memory usage

Spiral filling is an exception when the final matrix itself must be displayed after values are placed according to changing traversal directions.

Pattern Printing and Time Complexity

Nested loops do not automatically mean exactly operations. For a triangle, 1 + 2 + 3 + ... + n operations occur. This is n(n + 1) / 2. Asymptotically, this is O(n²).

For a square, n * n operations occur, which is also O(n²). Although both have the same Big-O complexity, their actual number of operations differs.

Interview-Oriented Variations

After understanding the basic patterns, practice changing one constraint at a time. Useful variations include:

  • Print values without spaces
  • Print pattern for user-provided n
  • Reverse the pattern vertically
  • Reverse each row horizontally
  • Generate the pattern using formulas instead of counters
  • Store the result in a matrix
  • Print only the boundary
  • Replace even values with 0
  • Replace odd values with 1
  • Generate a rectangular snake pattern
  • Generate anti-clockwise spiral traversal
  • Generate Pascal's Triangle using an array
  • Find a specific Pascal coefficient
  • Print concentric patterns with increasing values toward the center

These variations test whether you understand the underlying row-column relationship rather than memorizing output.

Number Patterns and Matrix Thinking

Simple patterns prepare you for matrix-based problems because both rely on coordinates. A matrix position is normally represented as matrix[row][col]. The value at that position may depend on:

  • Current row
  • Current column
  • Previous row
  • Previous column
  • Distance from a boundary
  • Direction of traversal

Concentric and spiral patterns are especially useful for developing this type of reasoning.

Choosing the Correct Technique

  • Use a counter when numbers must continue sequentially.
  • Use row or column variables when the displayed value directly matches its position.
  • Use parity when values alternate.
  • Use symmetry for pyramids and diamonds.
  • Use distance from edges for concentric patterns.
  • Use boundary variables for spiral traversal.
  • Use mathematical recurrence for Pascal's Triangle.

Recognizing the pattern category usually makes the implementation much simpler.

Practice Checklist

Before considering number patterns complete, you should be able to write these without copying code:

  • Sequential square
  • Repeated number triangle
  • Increasing triangle
  • Decreasing triangle
  • Reverse triangle
  • Floyd's Triangle
  • Pascal's Triangle
  • Palindromic pyramid
  • Alternating binary square
  • 0-1 triangle
  • Number diamond
  • Concentric number matrix
  • Snake matrix
  • Clockwise spiral matrix

More importantly, you should be able to explain why each inner-loop boundary and printed-value formula is correct.

Question Hint