KRECT - Counting K-Rectangle

Given a M*N square board. Each square contains a letter of the English alphabet ('A' .. 'Z').

A K-rectangle of the board is a rectangle whose sides are parallel to the sides of the board, and contains exactly K different types of letter.

For example, with this 4*3 board:


The rectangle [(1,1), (2,2)] is a 2-rectangle of the board because it contains 2 different letters: C and E.

Given M, N, K and the M*N board. Determine how many K-rectangles there are in the board.


The first line contains 3 integers M, N and K. (1 ≤ M, N ≤ 100, 1 ≤ K ≤ 26)

The following M lines, each contains N letters of the English alphabet ('A' .. 'Z')


Write one integer - the number of K-rectangles in the given board.


4 3 3


hide comments
sagar_june97p: 2019-06-18 18:23:07

O((n^2) * (m^2)) solution works. Do all possible constant time optimizations or you'll get TLE.

kshubham02: 2017-09-04 08:58:14

I need to stop getting swayed away by constraints and tags :/
Spent days trying for O(n*m*k) solution before coming to comments.

secta: 2016-03-03 08:49:36


xxbloodysantaxx: 2015-07-03 08:45:51

@Rafail it was informative , I never knew it but rather building up table was faster! O(1) queries you see.

Rafail Loizou: 2015-04-14 16:42:34

to avoid counting the 1s in the binary representation in O(A) linear time you should just use a built-in function. Search and you shall find!

Nivin : 2014-03-31 06:25:21

strict time limit :)

aristofanis: 2014-02-14 15:09:51

Got AC with O(n^4)
HINT: think like a computer; in binary :)

himalay: 2014-02-13 23:04:54

How is number of rectangles in given test case 12, mine answer is 7.

rishabhshinghal: 2014-01-18 11:30:16

my solution of complexity O(n^2*m^2*26) is not getting accpeted

Eternia: 2009-11-27 03:30:14

it's weird.. when I submitted my code(O(n^4)) and with LANG C++ 4.3.2 it passed all the test cases in 4.62 sec but when I submitted the same code with LANG C++ 4.0.0-8, the result it TLE...
Please tell me how this problem can occur. Thanks.

Added by:Race with time
Time limit:0.343s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO NODEJS PERL6 VB.NET
Resource:Based on problem CRECT - @vnoi