Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I need to solve the problem below in python3 (within 3 sec).

  • Problem definition:

A is a given (NxM) rectangle, filled with characters "a" to "z". Start from A[1][1] to A[N][M] collect all character which is only one in its row and column, print them as a string.

Input: N,M in first line (number of row and column 1<=N,M<=1000). Next N lines contain exactly M characters.

Output: A single string

Sample input1:
1 9
Sample output1:

Sample input2:
5 6
Sample output2:
from operator import itemgetter
N,M=[int(i) for i in input().split()]
for _ in range(N):
                                    # got the inputs
for row,word in enumerate(Words):   # going through each words
    Doubts=[]                       # collect chars only one in its row.
    for char in Chars:
            if (word.count(char)==1):
    for case in sorted(Doubts,key=itemgetter(1)):   #sorting by index
            doubtless=True                  #checking whether 1 in its column or not.
            for i in range(N):
                    if (Words[i][case[1]]==case[0] and i!=row):
            if (doubtless):
                    answer+=case[0] #if char is one in its row and column, adds to answer.
print (answer)

This is my code even it works, still not fast enough when N,M=1000. Any suggestion to improve the code faster would be helpful. Or any other ways to solve the given problem, as long as solution is in python3 and faster than mine.

share|improve this question
Not an observation about optimization, but why aren't you using PEP8 guidelines to write your code? It's not a dealbreaker by any means, but 1) Why don't you have spaces between operators and 2) Capital/CamelCase is usually reserved for class definitions. –  Joel Cornett Aug 17 '12 at 19:21
Thanks, but this time I wasn't wondering about how it looks. I was worrying about how it works :) –  Narankhuu Boldbaatar Aug 18 '12 at 2:31
For info, this has been cross-posted at StackOverflow. –  halfer Aug 18 '12 at 11:23
You didn't have to delete it, just declare the cross-posting. Then people can use the hyperlink to determine whether you still need assistance. It's about being considerate of other people's time, and as I said on the other thread, this has been part of netiquette for thirty years or so. –  halfer Aug 18 '12 at 11:49
I'll take a look at it a bit more in depth, but it appears that you're iterating over the elements in the matrix more times then necessary. You should be able to write an algorithm that does at most N * M * k_nm checks, where k is the number of unique letters in each row/column. (by unique I mean a member of the set of letters, I don't mean that they don't repeat in the sequence) –  Joel Cornett Aug 18 '12 at 23:03

2 Answers 2

I would suggest to create a 1000x1000 testcase and measure the performance before the optimization process. Please use the following test generator:

import os
import random

f = open('1000x1000.in','w')
f.write('1000 1000\n')
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(1000):
       f.write(''.join([ALPHABET[random.randint(0, len(ALPHABET)-1)] for _ in range(1000)]) + '\n')

After that just run it and measure the performance of your application. I got about 47 ms on my pretty old C2D E7200.

share|improve this answer

You could improve part of your loop.

for char in Chars:
        if (word.count(char)==1):

Can be done with list-comprehension.

    Doubts = [(char, word.index(char)) for char in Chars if word.count(char) == 1]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.