Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
My greedy O(N) solution

Mohammed Dh Abbas

Sep 5, 2024

class Solution: def largestPalindromic(self, num: str) -> str: # count the frequencies of the numbers from 9 - 0 in a map def build_counter(): counter = {str(i): 0 for i in range(10)} for n in num: counter[n] += 1 return counter counter = build_counter() remain = 0 # store the largest remaining number first_half = [] # store the first left half of the result result = [] # for the entire result # loop for all the number from 9 to 0 in decreasing order for i in range(9,0, -1): div = counter[str(i)] // 2 # take the division result rem = counter[str(i)] % 2 # the remaining # repeat i based on it's frequency divided by 2 for j in range(int(div)): first_half.append(str(i)) # find the largest remaining number if any if rem == 1: remain = max(remain, i) # now we compose the result result = first_half[:] # add the remain if any in the middle if remain > 0: result.append(str(remain)) # construct the right half as reverse of of the left half first_half.reverse() for char in first_half: result.append(str(char)) return "".join(result) if result else "0"

0

0

Comments
Comments

On this page