DEV Community

vc7
vc7

Posted on

1

LeetCode in Swift - 1072. Flip Columns For Maximum Number of Equal Rows

Problem

Data Structure

  • Hash map

Approach and the Routine

Base on the problem and the examples, a flip means, if there is a 0 will become 1 and if there is a 0 will become 1.

Normalize the rows

Because we only have to find the maximum number of all 0s and all 1s rows after a certain flipping of columns, which means we have to find the most appeared pattern.

01 -> 11 (Satisfied)
10 -> 00 (Satisfied)
Enter fullscreen mode Exit fullscreen mode

For example, after one flip of the column [0], we can get 2 rows are satisfied, so we can considering they are the same pattern.

01 -> 01
10 -> 01 (Normalized)
Enter fullscreen mode Exit fullscreen mode

To Count the appearance

We can use hash map to do the work, pattern as the key and count as the value.

// Routine 1st
01 -> [0, 1] -> [[0, 1]: 1]
10

// Routine 2st
01 
10 -> [0, 1] -> [[0, 1]: 2]
Enter fullscreen mode Exit fullscreen mode

Code

class Solution {
    func maxEqualRowsAfterFlips(_ matrix: [[Int]]) -> Int {
        // [pattern: count]
        var map = [[Int]: Int]()

        for row in matrix {
            let base = row[0]
            let pattern = row.map { $0 == base ? 0 : 1 }
            map[pattern, default: 0] += 1
        }

        return map.values.max() ?? 0
    }
}
Enter fullscreen mode Exit fullscreen mode

End of the post

That's it!

Please leave comment if you have any comments, thanks for your reading!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!