Code with Ramu

One destination for mastering interview coding

Learn, practice, and ace every interview coding question

num = -12345
rev = 0
n = abs(num)

while n > 0:
    rev = rev * 10 + n % 10
    n = n // 10

if num < 0:
    rev = -rev

print(rev)

def primefactors(n):
    factors = []
    # Factor out 2s
    while n % 2 == 0:
        factors.append(2)
        n = n // 2
    # Factor odd numbers
    i = 3
    while i * i <= n:
        while n % i == 0:
            factors.append(i)
            n = n // i
        i += 2
    # If remaining n is a prime number > 2
    if n > 2:
        factors.append(n)
    return factors

# Example
num = 84
print(primefactors(num))
numbers = [7, 4, 6, 3, 9, 1]
k = 3

# Sort in descending order
numbers.sort(reverse=True)

kthlargest = numbers[k-1]
print(kthlargest)
def ispower(n, x):
    if n < 1 or x <= 1:
        return False
    while n % x == 0:
        n = n // x
    return n == 1

# Example
print(ispower(16, 2))  # True, 16 = 2^4
print(ispower(20, 2))  # False
lst = [1, 2, 3, 2, 1, 4, 3]
seen = set()
result = []

for item in lst:
    if item not in seen:
        seen.add(item)
        result.append(item)

print(result)

#With Strings
print(''.join(result))

def longestuniquesubstring(s):
    start = 0
    maxlen = 0
    maxsub = ""
    seen = {}

    for end, char in enumerate(s):
        if char in seen and seen[char] >= start:
            start = seen[char] + 1
        seen[char] = end
        if end - start + 1 > maxlen:
            maxlen = end - start + 1
            maxsub = s[start:end+1]
    return maxsub

# Example
s = "abcabcbb"
print(longestuniquesubstring(s))
from collections import defaultdict

words = ["eat", "tea", "tan", "ate", "nat", "bat"]
anagrams = defaultdict(list)

for word in words:
    key = ''.join(sorted(word))
    anagrams[key].append(word)

# Convert to list of lists
result = list(anagrams.values())
print(result)

from collections import Counter

def findanagramsubstrings(s, pattern):
    lenp = len(pattern)
    patterncount = Counter(pattern)
    windowcount = Counter()
    resultindices = []

    for i, char in enumerate(s):
        # Add current character to the window
        windowcount[char] += 1

        # Remove the character that is left out of the window
        if i >= lenp:
            leftchar = s[i - lenp]
            if windowcount[leftchar] == 1:
                del windowcount[leftchar]
            else:
                windowcount[leftchar] -= 1

        # Compare window with pattern
        if windowcount == patterncount:
            resultindices.append(i - lenp + 1)

    return resultindices

# Example
s = "cbaebabacd"
pattern = "abc"
print(findanagramsubstrings(s, pattern))

def multiplystrings(num1, num2):
    if num1 == "0" or num2 == "0":
        return "0"
    
    m, n = len(num1), len(num2)
    result = [0] * (m + n)  # Maximum possible length

    # Reverse both numbers for easier calculation
    num1, num2 = num1[::-1], num2[::-1]

    # Multiply each digit
    for i in range(m):
        for j in range(n):
            result[i + j] += int(num1[i]) * int(num2[j])
            result[i + j + 1] += result[i + j] // 10  # Carry
            result[i + j] %= 10

    # Remove leading zeros and convert to string
    while len(result) > 1 and result[-1] == 0:
        result.pop()

    return ''.join(map(str, result[::-1]))

# Example
num1 = "123456789"
num2 = "987654321"
print(multiplystrings(num1, num2))

def isisomorphic(s1, s2):
    if len(s1) != len(s2):
        return False
    
    mappings1s2 = {}
    mappings2s1 = {}
    
    for c1, c2 in zip(s1, s2):
        # Check mapping from s1 -> s2
        if c1 in mappings1s2 and mappings1s2[c1] != c2:
            return False
        # Check mapping from s2 -> s1
        if c2 in mappings2s1 and mappings2s1[c2] != c1:
            return False
        
        mappings1s2[c1] = c2
        mappings2s1[c2] = c1
    
    return True

# Examples
print(isisomorphic("egg", "add"))  # True
print(isisomorphic("foo", "bar"))  # False
def convert(s: str, numRows: int) -> str:
    if numRows == 1 or numRows >= len(s):
        return s

    rows = [''] * numRows
    currentrow = 0
    goingdown = False

    for char in s:
        rows[currentrow] += char
        # Change direction when you reach top or bottom
        if currentrow == 0 or currentrow == numRows - 1:
            goingdown = not goingdown
        currentrow += 1 if goingdown else -1

    return ''.join(rows)

# Example usage:
s = "PAYPALISHIRING"
numRows = 3
print(convert(s, numRows)) 

# Output: "PAHNAPLSIIGYIR"

Posted in

Leave a comment