0% found this document useful (0 votes)
26 views2 pages

Answers

The document contains code snippets for four different programming problems: 1) a function that swaps the first two characters of two strings, 2) a function that formats a number with commas, 3) a function that finds the longest common prefix in a list of strings, and 4) a function that reorganizes a string using characters from a frequency counter.

Uploaded by

sethuraman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views2 pages

Answers

The document contains code snippets for four different programming problems: 1) a function that swaps the first two characters of two strings, 2) a function that formats a number with commas, 3) a function that finds the longest common prefix in a list of strings, and 4) a function that reorganizes a string using characters from a frequency counter.

Uploaded by

sethuraman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

 

1.  
def mix_up(a, b):
  # +++your code here+++
  # LAB(begin solution)
  a_swapped = b[:2] + a[2:]
  b_swapped = a[:2] + b[2:]
  return a_swapped + ' ' + b_swapped
  # LAB(replace solution)
  # return
  # LAB(end solution) 
 
2. 
string ans = ""; 
    string num = to_string(n); 
    int count = 0; 
    for (int i = num.size() - 1; 
         i >= 0; i--) { 
        count++; 
        ans.push_back(num[i]); 
        if (count == 3) { 
            ans.push_back(','); 
            count = 0; 
        } 
    } 
  
    reverse(ans.begin(), ans.end()); 
    if (ans.size() % 4 == 0) {   
        ans.erase(ans.begin()); 
    } 
    return ans; 
 
 
3. 
class Solution: 
    def longestCommonPrefix(self, strs: List[str]) -> str: 
        if len(strs) == 0: 
            return '' 

 
 

        res = 0 
        for i in range(len(strs[0])): 
            for j in range(len(strs)): 
                if len(strs[j])<=i or strs[0][i] != strs[j][i]: 
                    return strs[0][0:res] 
            res += 1 
        return strs[0][0:res] 
 
 
4.  
 def reorganizeString(self, S):
        res, c = [], Counter(S)
        pq = [(-value,key) for key,value in c.items()]
        heapq.heapify(pq)
        p_a, p_b = 0, ''
        while pq:
            a, b = heapq.heappop(pq)
            res += [b]
            if p_a < 0:
                heapq.heappush(pq, (p_a, p_b))
            a += 1
            p_a, p_b = a, b
        res = ''.join(res)
        if len(res) != len(S): return ""
        return res 
 
 
5.  
https://www.geeksforgeeks.org/find-possible-words-phone-digits/ 

You might also like