Skip to main content

Leetcode & HackerRank - Problems

STRINGS

1) Add Strings

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"
Solution:
def addStrings(self, num1: str, num2: str) -> str:
        s1, s2 = 0,0
        for i in num1:
            s1 = s1*10+int(i)
        for i in num2:
            s2 = s2*10+int(i)
            
        return str(s1+s2)
2) Number of Segments in a String

Given a string s, return the number of segments in the string.

segment is defined to be a contiguous sequence of non-space characters.

 

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1
Solution:
def countSegments(self, s: str) -> int:
    return len(s.split())
3)  Palindrome Number

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

  • For example, 121 is a palindrome while 123 is not.

 

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
class Solution:
    def isPalindrome(self, x: int) -> bool:
        num = x
        temp = 0
        while(num!=0):
            d = num%10
            temp=temp*10+d
            num=int(num/10)
            
        if temp==x:
            return True
        else:
            return False
4) Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

 

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
            
        s1=min(strs)
        s2=max(strs)
        i=0
        while i<(len(s1)):
            if(s1[i]!=s2[i]):
                return s1[:i]
            i=i+1
        if i==len(s1):
            return s1
        else:
            return ""
5) Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]
Solution:
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groupedWords = defaultdict(list)
        for word in strs:
            groupedWords["".join(sorted(word))].append(word)
            
        return [groupedWords[k] for k in groupedWords]

ARRAYS

1) Given a  2D Array:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

An hourglass in  is a subset of values with indices falling in this pattern in 's graphical representation:

a b c
  d
e f g

There are  hourglasses in . An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. The array will always be .

Example

-9 -9 -9  1 1 1 
 0 -9  0  4 3 2
-9 -9 -9  1 2 3
 0  0  8  6 6 0
 0  0  0 -2 0 0
 0  0  1  2 4 0

The  hourglass sums are:

-63, -34, -9, 12, 
-10,   0, 28, 23, 
-27, -11, -2, 10, 
  9,  17, 25, 18

The highest hourglass sum is  from the hourglass beginning at row , column :

0 4 3
  1
8 6 6

Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.

Function Description

Complete the function hourglassSum in the editor below.

hourglassSum has the following parameter(s):

  • int arr[6][6]: an array of integers

Returns

  • int: the maximum hourglass sum

Input Format

Each of the  lines of inputs  contains  space-separated integers .

Constraints

Output Format

Print the largest (maximum) hourglass sum found in .

Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample Output

19

Explanation

 contains the following hourglasses:

image

The hourglass with the maximum sum () is:

2 4 4
  2
1 2 4
Solution:
def hourglassSum(arr):
    # Write your code here
    maxSum = -63
    for i in range(4):
        for j in range(4):
            top = sum(arr[i][j:j+3])
            middle = arr[i+1][j+1]
            bottom = sum(arr[i+2][j:j+3])
            hourglass = top+middle+bottom
            if hourglass>maxSum:
                maxSum=hourglass
    return maxSum

2) A left rotation operation on an array shifts each of the array's elements  unit to the left. For example, if  left rotations are performed on array , then the array would become . Note that the lowest index item moves to the highest index in a rotation. This is called a circular array.

Given an array  of  integers and a number, , perform  left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.

Function Description

Complete the function rotLeft in the editor below.

rotLeft has the following parameter(s):

  • int a[n]: the array to rotate
  • int d: the number of rotations

Returns

  • int a'[n]: the rotated array

Input Format

The first line contains two space-separated integers  and , the size of  and the number of left rotations.
The second line contains  space-separated integers, each an .

Constraints

Sample Input

5 4
1 2 3 4 5

Sample Output

5 1 2 3 4
Solution 1: (Runtime error for some test cases)
def rotLeft(a, d):
    # Write your code here
    for j in range(d):
        temp = a[0]
        for i in range(len(a)-1):
            a[i]=a[i+1]
        a[len(a)-1]=temp
        print(a)
    return a        

Solution2:
def rotLeft(a, d):
    # Write your code here
    d=d%len(a)
    a = a[d:]+a[:d]
    return a        

Comments