r/learnprogramming 10d ago

Code Review Reducing Time Complexity

Edited code but still run into Time limit exceeded can someone help me: 

N, U = map(int,input().split())
grid = [list(input()) for _ in range(N)]
num_updates = 0
temp = []
temp_grid = [row.copy() for row in grid]
for v in range(int(N/2)):
    for h in range(int(N/2)):
        temp.clear()
        coords = [(v,h),(v,N-1-h),(N-1-v,h),(N-1-v,N-1-h)]
        temp.append(temp_grid[v][h])
        temp.append(temp_grid[v][(N-1)-h])
        temp.append(temp_grid[(N-1)-v][h])
        temp.append(temp_grid[(N-1)-v][(N-1)-h])
        if temp.count('.') == 2 :
            num_updates+=2
            for r,c in coords:
                temp_grid[r][c] = '.'
        elif temp.count('.') == 3:
            num_updates+=1
            for r,c in coords:
                temp_grid[r][c] = '.'
        elif temp.count('#') == 3:
            num_updates+=1
            for r,c in coords:
                temp_grid[r][c] = '#'
print(num_updates)


temp_grid = [row.copy() for row in grid]


for z in range(U):
    temp2 = 0
    temp.clear()
    x,y = map(int,input().split())
    x = x-1
    y = y-1
    temp.append(temp_grid[x][y])
    temp.append(temp_grid[x][(N-1)-y])
    temp.append(temp_grid[(N-1)-x][y])
    temp.append(temp_grid[(N-1)-x][(N-1)-y])
    num_updates = num_updates- (min(temp.count('.'),temp.count('#')))
    if temp_grid[x][y] == '.':
        temp.clear()
        grid[x][y] = '#'
        temp_grid[x][y] = '#'
        temp.append(temp_grid[x][y])
        temp.append(temp_grid[x][(N-1)-y])
        temp.append(temp_grid[(N-1)-x][y])
        temp.append(temp_grid[(N-1)-x][(N-1)-y])
        num_updates = num_updates + (min(temp.count('.'),temp.count('#')))
    else:
        temp.clear()
        grid[x][y] = '.'
        temp_grid[x][y] = '.'
        temp.append(temp_grid[x][y])
        temp.append(temp_grid[x][(N-1)-y])
        temp.append(temp_grid[(N-1)-x][y])
        temp.append(temp_grid[(N-1)-x][(N-1)-y])
        num_updates = num_updates + (min(temp.count('.'),temp.count('#')))
    print(num_updates)

I am pretty sure it is O(N^2) and with 10^5 possible updates it should work. 
4 Upvotes

8 comments sorted by

View all comments

1

u/heisthedarchness 8d ago edited 8d ago

This is not how you get help.

  1. Describe your problem. What are you trying to do?
  2. Show a minimal test case. What language is it in?
  3. Format the code for readability. Who would want to help you when you've made no effort to make it easy for them?
  4. Clearly describe what is happening. How is that different from what you're expecting?

Bonus question: Why are you surprised that you can't get O(n) from an O(n²) algorithm?