Accenture Coding Questions and Solutions (with code)

Prepare for the Accenture interview coding round with key tips on mastering arrays, strings, logic, and math basics.

Accenture Coding Questions and Solutions

Want to prepare for the Accenture interview coding round? We’ve heard it’s easy, we’ve heard it’s hard. The truth is, it’s straightforward if you prepare for the right things. This isn’t about memorizing endless problems – it’s about mastering the fundamentals they actually test on.

Based on previous candidate experiences, the coding test at Accenture is almost always the same format: two coding questions in 45 minutes. Your goal is to get at least one completely correct and the other one partially correct.

The questions are not designed to trick you; they are designed to see if you can write basic, functional code. The difficulty level is usually easy to medium, focusing on core logic, arrays, and strings.

Forget complex algorithms like dynamic programming or graph traversals. You won’t need them for the initial assessment. Focus on what matters. Let’s start.

Core Concepts You Absolutely Must Know

Don’t waste time on obscure topics. Your entire preparation should revolve around these four areas.

  • Arrays (or Lists in Python): This is their favorite topic. You need to be able to iterate, access elements, modify them, and perform simple calculations. Think sums, averages, finding elements, and basic sorting.
  • Strings: The second most common topic. Know how to manipulate strings: check characters, count vowels/consonants, reverse parts of a string, and validate patterns (like a password).
  • Basic Math and Logic: Many problems are just math problems disguised as coding questions. Prime numbers, greatest common divisor (GCD), base conversions, and simple series are common.
  • Functions: The problems will be given to you as a function you need to complete. You must understand how to accept arguments and return a value. All your code will be inside this function.

The languages you can use are typically C, C++, Java, Python, or .Net. We’ll use Python for the examples here because its syntax is clean and lets us focus on the logic.

Here are representative problems based on patterns that show up repeatedly. Master the logic here, and you’ll be fine.

Academy Pro

Java DSA Course

Learn Data Structures & Algorithms (DSA) in Java to excel in coding interviews and software development. Master linked lists, trees, graphs, heaps, hashing, sorting, and more while building efficient, optimized solutions.

2 projects
14 hrs
Java DSA Course

Question 1: The Classic Password Validator

This is a very common type of question you might encounter. It tests basic string manipulation and conditional logic.

The Problem:

You are given a function CheckPassword(str, n) which accepts a string str of length n. Implement the function to return 1 if the string is a valid password, otherwise return 0. A password is valid if it satisfies all the following conditions:

  • It must be at least 4 characters long.
  • It must contain at least one numeric digit.
  • It must contain at least one capital letter.
  • It must not have any spaces or slashes (/).
  • The first character cannot be a number.

The Solution (Python):

Python
def CheckPassword(s, n):
    # Condition 1: Length check
    if n < 4:
        return 0

    # Condition 5: First character check
    if s[0].isdigit():
        return 0

    has_digit = False
    has_capital = False

    for char in s:
        # Condition 4: Space or slash check
        if char == ' ' or char == '/':
            return 0
        
        # Condition 2: Digit check
        if char.isdigit():
            has_digit = True
            
        # Condition 3: Capital letter check
        if char.isupper():
            has_capital = True

    if has_digit and has_capital:
        return 1
    else:
        return 0

# Example Usage
password = "aB1_strong"
print(CheckPassword(password, len(password)))  # Output: 1

password2 = "aB 1"
print(CheckPassword(password2, len(password2))) # Output: 0

The Breakdown:

There is no magic here. We just translate the rules into code.

  • Initial Checks: The first two conditions (n < 4 and s[0].isdigit()) are easy to check upfront. If either fails, we return 0 immediately. This is efficient. No need to check the rest of the string if the basics are wrong.
  • Flags: We use boolean “flags” (has_digit, has_capital) to keep track of whether we’ve met certain conditions. They start as False.
  • The Loop: We loop through each character of the string once. This is important for performance.
  • Inside the Loop:
    • We check for invalid characters (‘ ‘ or ‘/’). If we find one, the password is bad, so we return 0 right away.
    • We use built-in string methods .isdigit() and .isupper(). If a character is a digit, we set has_digit = True. If it’s a capital letter, we set has_capital = True. Once a flag is True, it stays True.
  • Final Check: After the loop finishes, we check our flags. If has_digit AND has_capital are both True, it means all conditions were met. So we return 1. Otherwise, one of them was missing, and we return 0.

Question 2: Sum of Numbers Divisible by X and Y

This problem tests your understanding of loops and basic modulus arithmetic. It’s a common “filter and sum” pattern.

The Problem:

Implement the function Calculate(m, n), which takes two integers m and n. The function should calculate the sum of all numbers from 1 to m (inclusive) that are divisible by n.

The Solution (Python):

Python
def Calculate(m, n):
    total_sum = 0
    
    # Handle edge case where n is zero to avoid division error
    if n == 0:
        return 0

    for i in range(1, m + 1):
        if i % n == 0:
            total_sum += i
            
    return total_sum

# Example Usage
print(Calculate(20, 5)) # Output: 50 (5 + 10 + 15 + 20)
print(Calculate(10, 3)) # Output: 18 (3 + 6 + 9)

The Breakdown:

  • Initialization: We start with a variable total_sum set to 0. This will store our result.
  • Edge Case: If n is 0, division is impossible. The problem doesn’t specify what to do, but returning 0 is a safe and logical choice.
  • The Loop: We need to check every number from 1 up to m. The range(1, m + 1) in Python does exactly this.
  • The Condition: The core of the problem is the divisibility check. The modulus operator (%) gives you the remainder of a division. If i % n is 0, it means i is perfectly divisible by n.
  • The Summation: When the condition is true, we add the number i to our total_sum using total_sum += i.
  • The Return: After the loop has checked all the numbers, total_sum holds the final answer, and we return it.

Also Read: Conditional Statements in Python

Question 3: Second Largest Element in an Array

This is a frequently asked array manipulation question. It tests your ability to handle arrays and edge cases.

The Problem:

Write a function secondLargest(arr, n) that takes an array of integers arr of size n and returns the second largest element in the array. If no second largest element exists, return -1.

The Solution (Python):

Python
def secondLargest(arr, n):
    # Edge case: If array has less than 2 elements
    if n < 2:
        return -1

    largest = -float('inf')
    second_largest = -float('inf')

    for number in arr:
        if number > largest:
            second_largest = largest
            largest = number
        elif number > second_largest and number != largest:
            second_largest = number

    # If second_largest was never updated, it means all elements were the same
    if second_largest == -float('inf'):
        return -1
    else:
        return second_largest

# Example Usage
my_arr = [10, 5, 8, 20, 12]
print(secondLargest(my_arr, len(my_arr))) # Output: 12

my_arr2 = [5, 5, 5, 5]
print(secondLargest(my_arr2, len(my_arr2))) # Output: -1

The Breakdown:

This is more efficient than sorting the whole array first. Sorting takes O(n log n) time. This solution takes O(n) time because it only iterates through the list once.

  • Edge Case: If the array has fewer than two elements, a second largest is impossible. So we return -1 immediately.
  • Initialization: We create two variables, largest and second_largest. We initialize them to negative infinity (-float(‘inf’)) to ensure that the first element of any array with real numbers will be larger.
  • The Loop: We iterate through each number in the array.
  • Logic Branch 1 (number > largest): If the current number is greater than our current largest, it means we’ve found a new largest. The old largest now becomes the second_largest, and the current number becomes the new largest.
  • Logic Branch 2 (number > second_largest and number != largest): If the current number is not the new largest, we check if it’s bigger than the current second_largest. The number != largest part is crucial to handle duplicate largest values correctly. For an array like [20, 5, 20], we don’t want to set second_largest to 20.
  • Final Check: After the loop, if second_largest is still negative infinity, it means we never found a second largest element. This happens in an array like [5, 5, 5]. In this case, we return -1. Otherwise, we return the value we found.

Read: Python Data Types with Examples

Question 4: String Reversal by Words

Another common string manipulation task. This tests your ability to split, reverse, and join strings.

The Problem:

Given an input string s, reverse the string word by word. For example, if the input is “Accenture is great”, the output should be “great is Accenture”.

The Solution (Python):

Python
def reverseWords(s):
    # 1. Split the string into a list of words
    words = s.split()
    
    # 2. Reverse the list
    reversed_words = words[::-1]
    
    # 3. Join the reversed list back into a string
    output_string = " ".join(reversed_words)
    
    return output_string

# Example Usage
input_str = "Accenture is great"
print(reverseWords(input_str)) # Output: "great is Accenture"

The Breakdown:

Python’s built-in methods make this very simple. You just need to know they exist.

  1. s.split(): This method splits a string into a list of substrings based on a delimiter. By default, it splits by whitespace. So "Accenture is great" becomes ['Accenture', 'is', 'great'].
  2. words[::-1]: This is Python’s slice notation for reversing a list. It’s a clean and efficient way to create a reversed copy of the list. ['Accenture', 'is', 'great'] becomes ['great', 'is', 'Accenture'].
  3. " ".join(reversed_words): This is the opposite of split. The .join() method takes a list of strings and concatenates them into a single string, using the string it was called on as a separator. Here, we use a space (" ") as the separator. This turns ['great', 'is', 'Accenture'] back into "great is Accenture".

Suggested Read:

Question 5: Number Base Conversion

This type of problem tests your understanding of mathematical logic and how to implement it in code.

The Problem:

Implement a function dec_to_n(num, n) that takes a decimal integer num and a base n (where 2 <= n <= 36) and returns its representation in base n as a string.

The Solution (Python):

python
def dec_to_n(num, n):
    if num == 0:
        return "0"
        
    # Characters for bases greater than 10
    chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ""

    while num > 0:
        remainder = num % n
        result = chars[remainder] + result
        num = num // n # Integer division

    return result

# Example Usage
print(dec_to_n(10, 2)) # Output: "1010" (Binary)
print(dec_to_n(255, 16)) # Output: "FF" (Hexadecimal)

The Breakdown:

The logic is based on the standard algorithm for base conversion.

  1. Base Cases: If the input num is 0, the answer is always “0”. We handle this first.
  2. Character Map: For bases above 10, we need characters (A, B, C…). We create a string chars that maps an index to its character. chars[10] is ‘A’, chars[11] is ‘B’, and so on.
  3. The Loop: The conversion logic happens in a while loop that continues as long as num is greater than 0.
  4. remainder = num % n: We find the remainder when num is divided by the base n. This remainder gives us the rightmost digit of our result.
  5. result = chars[remainder] + result: We find the character corresponding to the remainder and prepend it to our result string. It’s important to prepend, not append, because we are generating the digits from right to left.
  6. num = num // n: We perform integer division to get the new num for the next iteration. This is like “chopping off” the last digit we just processed.
  7. Return: Once the loop finishes (num becomes 0), the result string holds the complete converted number.

How to Approach the Test

  1. Read Both Questions First: Don’t just start coding the first one you see. Spend one minute reading both questions. Identify the one you are more confident about.
  2. Attack the Easiest One First: Start with the question you know you can solve. Your goal is to get one question 100% correct. Secure those points. This boosts your confidence and guarantees you meet the “one complete” criteria.
  3. Time Management is Key: You have about 22 minutes per question. If you are stuck on a problem for more than 15 minutes, move on. It’s better to have one complete and one partial solution than two incomplete ones.
  4. Test With Your Own Cases: The online judge will have hidden test cases. Before you submit, run your code with your own examples. Think about edge cases: empty arrays, arrays with one element, zero, negative numbers. This will help you catch bugs.
  5. Don’t Overthink It: The problems are usually not as complex as they seem. Break them down into the simplest possible steps. If your solution seems overly complicated, you are probably missing a simpler approach. The answer is almost never a fancy algorithm. It’s loops, if statements, and basic data structures.

Also Read:

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.
Scroll to Top