Skip to content

0xspaanky/Java_TP_2

Repository files navigation

TP_2 - Array and Matrix Algorithms

Comprehensive collection of classic array and matrix algorithms including dynamic programming, prefix sums, spiral traversal, and mathematical puzzles.

Overview

Master fundamental array and matrix manipulation techniques through 10 algorithm challenges covering dynamic programming, optimization problems, and mathematical patterns.

Files Structure

TP_2/
├── LIS.java                      # Longest Increasing Subsequence (DP)
├── Pivots.java                   # Find pivot elements
├── Spirale.java                  # Generate spiral matrix
├── MaxRectangle.java             # Largest rectangle in binary matrix
├── PermutationCirculaire.java    # Check circular permutation
├── Kadane.java                   # Maximum subarray sum
├── Majoritaire.java              # Find majority element
├── ElementsManquants.java        # Find missing elements
├── Diagonales.java               # Compare diagonal sums
└── CarreMagique.java             # Verify magic square

Exercises

1. Longest Increasing Subsequence (LIS)

Problem: Find length of longest strictly increasing subsequence in array.

Approach: Dynamic Programming O(n²)

// dp[i] = length of LIS ending at index i
for (int i = 0; i < n; i++) {
    dp[i] = 1;  // Base case
    for (int j = 0; j < i; j++) {
        if (t[j] < t[i]) {
            dp[i] = Math.max(dp[i], dp[j] + 1);
        }
    }
}
return max(dp);

Example:

  • Input: [2, 1, 4, 2, 3, 5, 1, 7]
  • LIS: [1, 2, 3, 5, 7] → Length = 5

Screenshot: 1.png - LIS results for various test cases


2. Pivot Elements

Problem: Find elements where all left values ≤ pivot and all right values ≥ pivot.

Efficient Solution: Prefix Max + Suffix Min (O(n))

// Build prefixMax and suffixMin
for (int i = 1; i < n - 1; i++) {
    if (prefixMax[i-1] <= t[i] && suffixMin[i+1] >= t[i]) {
        // t[i] is a pivot
    }
}

Example:

  • Input: [3, 3, 3, 3]
  • Pivots: 3 3 (middle elements)

Screenshot: 2.png - Pivot detection results


3. Spiral Matrix Generation

Problem: Generate n×n matrix filled in spiral order (1 to n²).

Pattern:

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

Algorithm: Track boundaries (top, bottom, left, right) and fill layer by layer.

Screenshot: 3.png - Spiral matrices for n=1,2,3,4,5


4. Maximum Rectangle in Binary Matrix

Problem: Find largest rectangle containing only 1s in binary matrix.

Approach: For each row, treat as base and use histogram technique.

Example:

{0,1,1,0,1},
{1,1,1,1,0},
{1,1,1,1,0},
{1,1,0,0,1}

Result: Area = 8 (rectangle at rows 1-2, cols 0-3)

Screenshot: 4.png - Code and output showing max rectangle


5. Circular Permutation Check

Problem: Check if array is circular permutation of another by rotating.

Approach: Concatenate first array with itself and search for second array.

Example:

{4,5,1,2,3} and {1,2,3,4,5} → true (rotation exists)
{4,5,1,2,3} and {2,3,4,5,1} → true

Screenshot: 5.png - Circular permutation test results


6. Kadane's Algorithm (Maximum Subarray Sum)

Problem: Find contiguous subarray with maximum sum.

Algorithm:

int maxSum = t[0], currentSum = t[0];
for (int i = 1; i < n; i++) {
    currentSum = Math.max(t[i], currentSum + t[i]);
    maxSum = Math.max(maxSum, currentSum);
}

Example:

  • Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
  • Output: 6 (subarray: [4, -1, 2, 1])

Screenshot: 6.png - Kadane algorithm output (result: 6)


7. Majority Element (Boyer-Moore)

Problem: Find element appearing more than n/2 times.

Algorithm:

// Phase 1: Find candidate
int candidate = t[0], count = 1;
for (int i = 1; i < n; i++) {
    if (count == 0) candidate = t[i];
    count += (t[i] == candidate) ? 1 : -1;
}
// Phase 2: Verify candidate

Example:

  • Input: [3, 3, 4, 3, 5]
  • Output: 3 (appears 3 times out of 5)

Screenshot: 7.png - Majority element output (result: 3)


8. Missing Elements

Problem: Find all missing elements in range [1, n] given array of size n-k.

Approach: Use boolean array or mathematical sum comparison.

Example:

  • Input: [1, 3, 5] (n=5)
  • Output: 2 4 (missing elements)

Screenshot: 8.png - Missing elements output (2 4)


9. Diagonal Comparison

Problem: Calculate and compare main diagonal and secondary diagonal sums.

Formula:

// Main diagonal: sum of m[i][i]
// Secondary diagonal: sum of m[i][n-1-i]

Example:

{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
  • Main: 1+5+9 = 15
  • Secondary: 3+5+7 = 15
  • Difference = 0

Screenshot: 9.png - Diagonal comparison output


10. Magic Square Verification

Problem: Check if n×n matrix is a magic square (all rows, columns, diagonals have same sum).

Conditions:

  1. All row sums equal
  2. All column sums equal
  3. Both diagonal sums equal
  4. All sums equal to magic constant: n(n²+1)/2

Example:

{8, 1, 6},
{3, 5, 7},
{4, 9, 2}

All sums = 15 → Magic Square ✓

Screenshot: 10.png - Magic square verification (Carré magique)


Algorithm Complexities

Algorithm Time Space Technique
LIS O(n²) O(n) Dynamic Programming
Pivots O(n) O(n) Prefix/Suffix arrays
Spirale O(n²) O(n²) Layer traversal
MaxRectangle O(n²m) O(m) Histogram technique
Permutation O(n) O(1) String matching
Kadane O(n) O(1) Greedy/DP
Majoritaire O(n) O(1) Boyer-Moore
Missing O(n) O(n) Boolean marking
Diagonales O(n²) O(1) Matrix traversal
CarreMagique O(n²) O(1) Sum verification

Key Concepts

Dynamic Programming (LIS)

  • Break problem into overlapping subproblems
  • Store solutions to avoid recomputation
  • Build solution bottom-up or top-down with memoization

Prefix/Suffix Technique (Pivots)

  • Precompute cumulative information
  • Answer queries in O(1) after O(n) preprocessing
  • Common for range queries

Kadane's Algorithm

  • Track local and global maximum
  • Decide to extend or start new subarray
  • Classic greedy approach

Boyer-Moore Voting

  • Find majority element in O(1) space
  • Candidate selection + verification phases
  • Optimal for frequency problems

Compilation & Execution

# Compile individual file
javac LIS.java
java LIS

# Compile all
javac *.java

# Run specific algorithm
java Pivots
java Kadane
java CarreMagique

Test Cases Summary

LIS: Empty, single, decreasing, increasing, mixed Pivots: Sorted, reverse, duplicates, no pivots Spiral: n=1 to n=5 Kadane: All negative, all positive, mixed Majority: Clear majority, no majority Magic Square: Valid and invalid squares

Key Takeaways

  1. Dynamic Programming - Store intermediate results for optimal solutions
  2. Prefix/Suffix - Precompute for efficient range queries
  3. Greedy Algorithms - Make locally optimal choices (Kadane)
  4. Space-Time Tradeoff - Use extra space to improve time complexity
  5. Mathematical Patterns - Recognize formulas (magic square constant)

Technologies

  • Java - Core arrays and matrix manipulation
  • Algorithms - Dynamic Programming, Greedy, Prefix Sums

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages