0% found this document useful (0 votes)
30 views11 pages

Accenture Coding Test Vardhaman Material

Uploaded by

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

Accenture Coding Test Vardhaman Material

Uploaded by

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

1.

Given an array of integers nums and an integer target, return indices of the two numbers such
that they add up to target.
2. Given a string s, find the length of the longest substring without repeating characters.
3. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of
the two sorted arrays.
4. Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to
go outside the signed 32-bit integer range [-231, 231- 1], then return 0.
5. Given an integer x, return true if x is a palindrome, and false otherwise
6. Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
7. 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 "".
8. Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one
sorted list. The list should be made by splicing together the nodes of the first two lists. Return
the head of the merged linked list.
9. Wildcard Matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support
for '?' and '*' where:
-'?' Matches any single character.
-'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
10. Set Matrix Zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
11. Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and
return false if every element is distinct.
12. Palindrome Linked List:
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
13. Add Digits
Given an integer num, repeatedly add all its digits until the result has only one digit, and return
it.
14. Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.
15. Bulb Switcher
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every
second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For
the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
Return the number of bulbs that are on after n rounds.
16. Fibonacci Number
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci
sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).
17. Running Sum of 1d Array
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…
nums[i]).
Return the running sum of nums.
18. Count Odd Numbers in an Interval Range
Given two non-negative integers low and high. Return the count of odd numbers between low
and high (inclusive).
19. Richest Customer Wealth
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i th
customer has in the jth bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest
customer is the customer that has the maximum wealth.
20. Substrings of Size Three with Distinct Characters
A string is good if there are no repeated characters. Given a string s, return the number of good
substrings of length three in s. Note that if there are multiple occurrences of the same substring,
every occurrence should be counted. A substring is a contiguous sequence of characters in a
string.
21. Find Subsequence of Length K With the Largest Sum
You are given an integer array nums and an integer k. You want to find a subsequence of nums
of length k that has the largest sum.
Return any such subsequence as an integer array of length k. A subsequence is an array that can
be derived from another array by deleting some or no elements without changing the order of
the remaining elements.

Solutions:
1. Given an array of integers nums and an integer target, return indices of the two numbers
such that they add up to target.

Sol:class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
M = {}
for i in range(n):
x = target - nums[i]
if nums[i] in M:
return [M[nums[i]],i]
else:
M[x] = i

2. Given a string s, find the length of the longest substring without repeating characters.

Sol: class Solution:


def lengthOfLongestSubstring(self, s: str) -> int:
start=0
count=0
for end in range(1,len(s)+1):
if len(set(s[start:end]))==len(s[start:end]):
if (end-start+1)>count:
count=len(s[start:end])
else:
start+=1
return(count)

3. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median
of the two sorted arrays.

Sol: class Solution:


def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
arr3: List[int] = nums1 + nums2
arr3.sort()
len3: int = len(arr3)

if not len3:
return None
if len3 % 2 == 0:
return arr3[len3//2]
else:
return arr3[len3//2-1] / 2.0 + arr3[len3//2] / 2.0

4. Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the
value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Sol:class Solution:
def reverse(self, x: int) -> int:

mxStr = '2147483647'

ansLst = reversed(str(abs(x)))

ansStr = ''.join(ansLst).rjust(10,'0')

if ansStr > mxStr: return 0

return int(ansStr)*(1 - 2*(x < 0))

5. Given an integer x, return true if x is a palindrome, and false otherwise

Sol: def isPalindrome(self, x: int) -> bool:


if x < 0:
return False

return str(x) == str(x)[::-1]

6. Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

SOl: class Solution:


def romanToInt(self, s: str) -> int:
translations = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
number = 0
s = s.replace("IV", "IIII").replace("IX", "VIIII")
s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
for char in s:
number += translations[char]
return number

7. 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 "".

Solution:

class Solution:
def longestCommonPrefix(self, v: List[str]) -> str:
ans=""
v=sorted(v)
first=v[0]
last=v[-1]
for i in range(min(len(first),len(last))):
if(first[i]!=last[i]):
return ans
ans+=first[i]
return ans

8. Merge Two Sorted Lists


You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of
the first two lists.
Return the head of the merged linked list.

Solution:

class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2

9. Wildcard Matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support
for '?' and '*' where:
-'?' Matches any single character.
-'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).

Solution:

class Solution:
def isMatch(self, s: str, p: str) -> bool:

def remove_duplicate_stars(p: str) -> str:


new_string = []
for char in p:
if not new_string or char != '*':
new_string.append(char)
elif new_string[-1] != '*':
new_string.append(char)
return ''.join(new_string)

def helper(s: str, p: str) -> bool:


if (s, p) in dp:
return dp[(s, p)]

if p == s or p == '*':
dp[(s, p)] = True
elif p == '' or s == '':
dp[(s, p)] = False
elif p[0] == s[0] or p[0] == '?':
dp[(s, p)] = helper(s[1:], p[1:])
elif p[0] == '*':
dp[(s, p)] = helper(s, p[1:]) or helper(s[1:], p)
else:
dp[(s, p)] = False

return dp[(s, p)]

dp = {}
p = remove_duplicate_stars(p)
return helper(s, p)

10. Set Matrix Zeroes


Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.

Solution:

class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
R = len(matrix)
C = len(matrix[0])
rows, cols = set(), set()

# Essentially, we mark the rows and columns that are to be made zero
for i in range(R):
for j in range(C):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)

# Iterate over the array once again and using the rows and cols sets, update the elements
for i in range(R):
for j in range(C):
if i in rows or j in cols:
matrix[i][j] = 0

11. Contains Duplicate


Given an integer array nums, return true if any value appears at least twice in the array, and
return false if every element is distinct.

Solution:

class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
n = len(nums)
for i in range(n - 1):
for j in range(i + 1, n):
if nums[i] == nums[j]:
return True
return False

12. Palindrome Linked List:


Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Solution:

class Solution:
def isPalindrome(self, head: ListNode) -> bool:
def reverseList(head: ListNode) -> ListNode:
prev = None
curr = head

while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next

return prev

slow = head
fast = head

while fast and fast.next:


slow = slow.next
fast = fast.next.next

if fast:
slow = slow.next
slow = reverseList(slow)

while slow:
if slow.val != head.val:
return False
slow = slow.next
head = head.next

return True

13. Add Digits


Given an integer num, repeatedly add all its digits until the result has only one digit, and return
it.

Solution:

class Solution:
def addDigits(self, num: int) -> int:

if num == 0:
return 0
return num % 9 if num % 9 != 0 else 9
14. Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.

Solution:

class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp=[0]*(len(nums))
dp[0]=1
for i in range(1,len(nums)):
maxi=0
for j in range(0,i):
if(nums[i]>nums[j]):
maxi=max(maxi,dp[j])
dp[i]=1+maxi

return max(dp)

15. Bulb Switcher


There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every
second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For
the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
Return the number of bulbs that are on after n rounds.

Solution:

class Solution:
def bulbSwitch(self, n: int) -> int:
return isqrt(n)

16. Fibonacci Number


The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci
sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).

Solution:

class Solution:
def fib(self, n: int) -> int:
def fib(n):
if Fib[n] != -1:
return Fib[n]
Fib[n] = fib(n-1) + fib(n-2)
return Fib[n]
if n == 0:
return 0
if n == 1:
return 1
Fib = [-1 for _ in range(n+1)]
Fib[0] = 0
Fib[1] = 1
return fib(n)

17. Running Sum of 1d Array


Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…
nums[i]).

Return the running sum of nums.

Solution:

# Time Complexity : O(n)


# Space Complexity : O(n)
class Solution(object):
def runningSum(self, nums):
# Create an output array of size equal to given nums size...
output = [0] * len(nums)
# Set output[0] = nums[0]...
output[0] = nums[0]
# Traverse all elements through the for loop...
for idx in range(1, len(nums)):
# Storing the running sum...
output[idx] = output[idx - 1] + nums[idx]
return output # Return the running sum of nums...

18. Count Odd Numbers in an Interval Range


Given two non-negative integers low and high. Return the count of odd numbers between low
and high (inclusive).

Solution:

class Solution:
def countOdds(self, low: int, high: int) -> int:
if(low%2!=0 and high%2!=0):
return int((((high-low)+1)/2)+1)

if(low%2==0 and high%2==0):


return int(((high-low)+1)/2)

if(low%2!=0):
return int(((((high-low)+1)-2)/2)+1)

else:
return int(((high-low)/2)+1)

19. Richest Customer Wealth


You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith
customer has in the jth bank. Return the wealth that the richest customer has.

A customer's wealth is the amount of money they have in all their bank accounts. The richest
customer is the customer that has the maximum wealth.

Solution:

class Solution:
def maximumWealth(self, accounts: List[List[int]]) -> int:
return max([sum(acc) for acc in accounts])

20. Substrings of Size Three with Distinct Characters


A string is good if there are no repeated characters.

Given a string s, return the number of good substrings of length three in s.

Note that if there are multiple occurrences of the same substring, every occurrence should be
counted.

A substring is a contiguous sequence of characters in a string.

Solution:

class Solution:
def countGoodSubstrings(self, s: str) -> int:
count=0
for i in range(len(s)-2):
x=s[i:i+3]
if x.count(x[0])==1 and x.count(x[1])==1 and x.count(x[2])==1:
count+=1
return count

21. Find Subsequence of Length K With the Largest Sum


You are given an integer array nums and an integer k. You want to find a subsequence of nums
of length k that has the largest sum.
Return any such subsequence as an integer array of length k.
A subsequence is an array that can be derived from another array by deleting some or no
elements without changing the order of the remaining elements.
Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
val_and_index = sorted([(num, i) for i, num in enumerate(nums)])
return [num for num, i in sorted(val_and_index[-k :], key=lambda x: x[1])]

You might also like