0% found this document useful (0 votes)
6 views13 pages

Java Solutions

The document outlines Java solutions for 12 coding problems, including algorithms for data structures and string manipulation. Each problem includes a description of the approach, Java code implementation, and complexity analysis. The problems cover various patterns such as sliding window, hash maps, and the Sieve of Eratosthenes, providing a comprehensive guide for campus hiring assessments at Accenture.

Uploaded by

2210030151
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)
6 views13 pages

Java Solutions

The document outlines Java solutions for 12 coding problems, including algorithms for data structures and string manipulation. Each problem includes a description of the approach, Java code implementation, and complexity analysis. The problems cover various patterns such as sliding window, hash maps, and the Sieve of Eratosthenes, providing a comprehensive guide for campus hiring assessments at Accenture.

Uploaded by

2210030151
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

ACCENTURE 2026 CAMPUS HIRING

Round 3 — Java Solutions Reference


All 12 Problems • Clean Java 8+ Solutions • With Explanation & Complexity
⚠ Java users: always scroll to the top of the template and COMMENT OUT the 'throw new Exception(...)'
line first.

SECTION A — DSA SOLUTIONS


P1 Cave Energy Sum
Pattern: Sliding Window / Nested Loop | Time: O(N) | Space: O(1)
Approach
For each index i, sum elements from max(0, i-2) to i using an inner loop. Accumulate into total.

Java Solution
import [Link];

public class CaveEnergy {


// throw new Exception(); <-- COMMENT THIS OUT

public static int caveEnergy(int N, int[] A) {


int total = 0;
for (int i = 0; i < N; i++) {
int start = [Link](0, i - 2);
for (int j = start; j <= i; j++) {
total += A[j];
}
}
return total;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link]();
int[] A = new int[N];
for (int i = 0; i < N; i++) A[i] = [Link]();
[Link](caveEnergy(N, A));
}
}

💡 Complexity: O(N) time — each element is added at most 3 times (window size ≤ 3). O(1) space.

P2 Password Validator
Pattern: String scan with boolean flags | Time: O(N) | Space: O(1)
Approach
Check length and first char upfront. Use flags for digit and uppercase. Reject on space or slash immediately.

Java Solution
public class PasswordValidator {
public static int checkPassword(String s, int n) {
// Rule 1: min length 4
if (n < 4) return 0;
// Rule 5: first char must not be digit
if ([Link]([Link](0))) return 0;

boolean hasDigit = false;


boolean hasUpper = false;

for (char c : [Link]()) {


// Rule 4: no space or slash
if (c == ' ' || c == '/') return 0;
if ([Link](c)) hasDigit = true;
if ([Link](c)) hasUpper = true;
}

return (hasDigit && hasUpper) ? 1 : 0;


}

public static void main(String[] args) {


[Link](checkPassword("aB1_strong", 10)); // 1
[Link](checkPassword("aB 1cd", 6)); // 0
}
}

⚠ All 5 conditions must pass simultaneously. Returning 0 early on Rule 4 saves time on long strings.

P3 Sum of Numbers Divisible by X or Y


Pattern: Loop + modulo accumulator | Time: O(N) | Space: O(1)
Approach
Iterate 1 to N. For each number, add it to the total if divisible by X OR Y. The 'or' operator prevents double-
counting.

Java Solution
import [Link];

public class SumDivisible {

public static long sumDivisible(int N, int X, int Y) {


long total = 0; // use long to avoid overflow for large N
for (int i = 1; i <= N; i++) {
if (i % X == 0 || i % Y == 0) {
total += i;
}
}
return total;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link](), X = [Link](), Y = [Link]();
[Link](sumDivisible(N, X, Y));
}
}

💡 Use long for total — if N = 10^6 and all values qualify, sum can exceed Integer.MAX_VALUE.
P4 Second Largest Element in Array
Pattern: Single-pass two-variable tracking | Time: O(N) | Space: O(1)
Approach
Track 'largest' and 'secondLargest' in one pass. Only update secondLargest when a strictly smaller (but larger
than current second) value is found.

Java Solution
import [Link];

public class SecondLargest {

public static int secondLargest(int[] A) {


int largest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;

for (int num : A) {


if (num > largest) {
second = largest; // old largest becomes second
largest = num;
} else if (num > second && num != largest) {
second = num; // update second only if distinct
}
}
return (second == Integer.MIN_VALUE) ? -1 : second;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link]();
int[] A = new int[N];
for (int i = 0; i < N; i++) A[i] = [Link]();
[Link](secondLargest(A));
}
}

⚠ The 'num != largest' check ensures distinctness. Without it, [5,5] would return 5 instead of -1.

P5 Reverse Words in a String


Pattern: Split / reverse / join | Time: O(N) | Space: O(N)
Approach
Split the string by spaces into a words array, reverse it, then join with a single space.

Java Solution
public class ReverseWords {

public static String reverseWords(String s) {


// trim() handles any leading/trailing spaces
String[] words = [Link]().split("\\s+");
StringBuilder sb = new StringBuilder();

for (int i = [Link] - 1; i >= 0; i--) {


[Link](words[i]);
if (i > 0) [Link](" ");
}
return [Link]();
}
public static void main(String[] args) {
[Link](reverseWords("Hello World")); // World Hello
[Link](reverseWords("I love coding")); // coding love I
[Link](reverseWords("one two three four"));// four three two one
}
}

💡 \\s+ in split() handles multiple spaces between words — safer than splitting on a single space.

P6 Decimal to Binary Conversion


Pattern: Repeated division | Time: O(log N) | Space: O(log N)
Approach
Repeatedly divide N by 2, prepend each remainder to a StringBuilder. Handle N=0 as a special case.

Java Solution
import [Link];

public class DecimalToBinary {

public static String decToBin(int n) {


if (n == 0) return "0";

StringBuilder sb = new StringBuilder();


while (n > 0) {
[Link](0, n % 2); // prepend remainder
n /= 2;
}
return [Link]();
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link](decToBin([Link]()));
// Tests: 10->1010, 0->0, 255->11111111
}
}

⚠ Do NOT use [Link]() or other built-ins — the problem explicitly forbids them.

P7 Count Prime Numbers in Range [L, R]


Pattern: Sieve of Eratosthenes | Time: O(R log log R) | Space: O(R)
Approach
Build a boolean sieve up to R. Mark all composites. Count unmarked (prime) indices from L to R.

Java Solution
import [Link];

public class CountPrimes {

public static int countPrimes(int L, int R) {


// Sieve of Eratosthenes
boolean[] isComposite = new boolean[R + 1];
isComposite[0] = isComposite[1] = true; // 0,1 not prime
for (int i = 2; (long) i * i <= R; i++) {
if (!isComposite[i]) {
for (int j = i * i; j <= R; j += i) {
isComposite[j] = true;
}
}
}

int count = 0;
for (int i = L; i <= R; i++) {
if (!isComposite[i]) count++;
}
return count;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int L = [Link](), R = [Link]();
[Link](countPrimes(L, R));
}
}

💡 Cast to (long) i*i to avoid integer overflow when i is large. Start marking from i*i (not 2*i) for efficiency.

P8 Two Sum Target Pair


Pattern: HashSet complement lookup | Time: O(N) | Space: O(N)
Approach
Iterate the array. For each number, check if (target - num) exists in the set. If yes, found the pair. Otherwise add
num to the set.

Java Solution
import [Link].*;

public class TwoSum {

public static void twoSum(int[] A, int T) {


Set<Integer> seen = new HashSet<>();

for (int num : A) {


int complement = T - num;
if ([Link](complement)) {
int a = [Link](num, complement);
int b = [Link](num, complement);
[Link]("YES");
[Link](a + " " + b);
return;
}
[Link](num);
}
[Link]("NO");
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link](), T = [Link]();
int[] A = new int[N];
for (int i = 0; i < N; i++) A[i] = [Link]();
twoSum(A, T);
}
}
⚠ Print the smaller value first using [Link]/[Link] — the problem requires ascending order output.

SECTION A (CONT.) — RECALLED & MAP PROBLEMS


P9 Password Hashing (Caesar Cipher Variant)
Pattern: Character-by-character ASCII shift | Time: O(N) | Space: O(N)
Approach
For each character: if lowercase shift in a-z range with mod 26; if uppercase shift in A-Z range; if digit shift in 0-9
range with mod 10; else keep as-is.

Java Solution
import [Link];

public class PasswordHash {

public static String hashPassword(String password, int K) {


int letterShift = K % 26; // handles K > 26
int digitShift = K % 10; // handles K > 10
StringBuilder result = new StringBuilder();

for (char c : [Link]()) {


if (c >= 'a' && c <= 'z') {
// shift within a-z with wrap-around
[Link]((char)('a' + (c - 'a' + letterShift) % 26));

} else if (c >= 'A' && c <= 'Z') {


// shift within A-Z with wrap-around
[Link]((char)('A' + (c - 'A' + letterShift) % 26));

} else if (c >= '0' && c <= '9') {


// shift within 0-9 with wrap-around
[Link]((char)('0' + (c - '0' + digitShift) % 10));

} else {
// special character — unchanged
[Link](c);
}
}
return [Link]();
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
String p = [Link]();
int K = [Link]();
[Link](hashPassword(p, K));
// Test: Hello@123 K=3 -> Khoor@456
// Test: xyz K=3 -> abc (wrap-around)
// Test: aB3!z K=27 -> bC4!a (K>26 reduced)
}
}

💡 The formula 'a' + (c - 'a' + shift) % 26 is the cleanest Java idiom — no if-else chains needed for wrap-around.
P10 Group Anagrams & Count
Pattern: HashMap<String,List> with sorted key | Time: O(N·L log L) | Space: O(N·L)
Approach
Sort each string's chars to make the map key. All strings with the same sorted key are anagrams. Collect groups,
sort by size descending.

Java Solution
import [Link].*;

public class GroupAnagrams {

public static void groupAnagrams(String[] words) {


// Map: sorted_key -> list of original words
Map<String, List<String>> map = new LinkedHashMap<>();

for (String word : words) {


char[] chars = [Link]();
[Link](chars); // sort chars to form key
String key = new String(chars);
[Link](key, k -> new ArrayList<>()).add(word);
}

// Collect and sort groups: descending by size, then by key name


List<[Link]<String, List<String>>> groups =
new ArrayList<>([Link]());

[Link]((a, b) -> {
int sizeComp = [Link]().size() - [Link]().size();
return sizeComp != 0 ? sizeComp : [Link]().compareTo([Link]());
});

[Link]([Link]()); // number of distinct groups


for ([Link]<String, List<String>> e : groups) {
[Link]([Link]() + ": ");
[Link]([Link](" ", [Link]()));
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link](); [Link]();
String[] words = new String[N];
for (int i = 0; i < N; i++) words[i] = [Link]().trim();
groupAnagrams(words);
}
}

⚠ The comparator sorts by SIZE desc first, then KEY name asc as tiebreaker — both are required for full marks.
💡 computeIfAbsent is cleaner than manually checking containsKey. It creates the list only if the key is new.

P11 Common Characters with Minimum Frequency


Pattern: Two frequency HashMaps + intersection | Time: O(N+M) | Space: O(1) — only 26 chars
Approach
Build frequency maps for both strings. Find common keys (intersection). For each common character, output the
minimum of its two frequencies. Sort output alphabetically.
Java Solution
import [Link].*;

public class CommonCharacters {

public static void commonChars(String s1, String s2) {


Map<Character, Integer> freq1 = new HashMap<>();
Map<Character, Integer> freq2 = new HashMap<>();

// Build frequency maps


for (char c : [Link]())
[Link](c, 1, Integer::sum);
for (char c : [Link]())
[Link](c, 1, Integer::sum);

// Find intersection — characters present in BOTH


List<Character> common = new ArrayList<>();
for (char c : [Link]()) {
if ([Link](c)) [Link](c);
}

if ([Link]()) {
[Link]("NONE");
return;
}

// Sort alphabetically before printing


[Link](common);
for (char c : common) {
int minFreq = [Link]([Link](c), [Link](c));
[Link](c + " " + minFreq);
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
String s1 = [Link](), s2 = [Link]();
commonChars(s1, s2);
// Test: aabbcc abc -> a 1 / b 1 / c 1
// Test: hello world -> l 1 / o 1
// Test: abc xyz -> NONE
}
}

💡 merge(c, 1, Integer::sum) is cleaner than getOrDefault(c,0)+1. Both work fine in the exam.

P12 Count Subarrays with Sum Equal to K


Pattern: Prefix Sum + HashMap | Time: O(N) | Space: O(N) | Difficulty: Hard
Approach
Maintain a running prefix sum. At each index, check if (prefixSum - K) exists in the map — if yes, those are valid
subarrays ending here. Initialise map with {0: 1} before the loop.

Java Solution
import [Link].*;

public class SubarraySum {

public static int subarraySum(int[] A, int K) {


// prefixCount stores how many times each prefix sum has occurred
Map<Integer, Integer> prefixCount = new HashMap<>();
[Link](0, 1); // CRITICAL: empty prefix has sum 0

int prefixSum = 0;
int count = 0;

for (int num : A) {


prefixSum += num;

// If (prefixSum - K) was seen before, those subarrays sum to K


count += [Link](prefixSum - K, 0);

// Record current prefix sum


[Link](prefixSum, 1, Integer::sum);
}
return count;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link](), K = [Link]();
int[] A = new int[N];
for (int i = 0; i < N; i++) A[i] = [Link]();
[Link](subarraySum(A, K));
// Test: [1,1,1,2,3] K=2 -> 4
// Test: [0,0,0,0] K=0 -> 10
// Test: [1,-1,1,-1,1] K=-1 -> 4
}
}

⚠ NEVER forget [Link](0, 1) before the loop. Without it, subarrays starting at index 0 that sum to K are
missed — you lose marks even if the rest is correct.
💡 This also handles negative numbers and K=0 correctly — unlike the brute force O(N²) nested loop approach.

SECTION B — SQL SOLUTIONS


SQL runs on MySQL 8.0 in the Accenture platform — no Java needed. Clean query templates below.

P13 SQL 1 — High-Earning Employees


SELECT [Link], [Link], d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.dept_id
WHERE [Link] > 50000
ORDER BY [Link] DESC;

P14 SQL 2 — Department Headcount Filter


SELECT department_id,
COUNT(*) AS emp_count,
ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 3
ORDER BY avg_salary DESC;

P15 SQL 3 — Above-Average Earners in Mumbai


SELECT [Link], [Link], d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.dept_id
WHERE [Link] > (SELECT AVG(salary) FROM employees)
AND ([Link] = 'Mumbai' OR e.department_id IS NULL)
ORDER BY [Link] DESC;

P16 SQL 4 — Products with No Orders


SELECT p.product_id, p.product_name
FROM products p
LEFT JOIN orders o ON p.product_id = o.product_id
WHERE o.order_id IS NULL
ORDER BY p.product_id ASC;

P17 SQL 5 — Second Highest Salary


SELECT MAX(salary) AS SecondHighestSalary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

-- Returns NULL automatically when no second value exists.


-- Do NOT use: ORDER BY salary DESC LIMIT 1 OFFSET 1
-- (that approach throws an error when only one distinct salary exists)

P18 SQL 6 — Monthly Sales Report


SELECT MONTH(order_date) AS order_month,
COUNT(*) AS total_orders,
ROUND(SUM(quantity*unit_price),2) AS total_revenue
FROM orders
WHERE YEAR(order_date) = 2024
GROUP BY MONTH(order_date)
HAVING COUNT(*) >= 5
ORDER BY order_month ASC;

QUICK REFERENCE — Java Patterns Cheat Sheet

Pattern Java Idiom Used In


Frequency map [Link](c, 1, P9, P10, P11
Integer::sum)

Map with list [Link](key, k- P10


>new ArrayList<>())

Prefix sum map [Link](0,1) before P12


loop

Char shift 'a'+(c-'a'+shift)%26 P9

Sort chars char[] a=[Link](); P10


[Link](a)

Two-pointer int l=0, r=n-1; while(l<r) P4, P5


{...l++;r--;}

Long overflow long total=0 when N can be P3


10^6+

Sieve start for j = i*i (not 2*i) P7


NULL-safe SQL getOrDefault(key, 0) P12

String split [Link]().split("\\s+") P5

★ CONFIRMED REAL EXAM QUESTIONS — JAVA


SOLUTIONS ★
Photographed directly from the Accenture platform • Java solutions for exact exam questions

PR1 Consecutive Character Replacement [Backend Q1]


Pattern: Two-pass String scan | Time: O(N) | Space: O(N) | ★ Confirmed on platform
Approach
Pass 1: scan the string, whenever 2+ consecutive identical chars are found replace the whole run with a single '#'.
Pass 2: collapse any run of 2+ '#' into a single '#'. Both passes can be done in one build loop.

Java Solution
public class ConsecutiveReplace {

public static String replaceConsecutive(String s) {


if (s == null || [Link]()) return s;

// ── Pass 1: replace 2+ consecutive identical chars with '#' ──


StringBuilder pass1 = new StringBuilder();
int i = 0;
while (i < [Link]()) {
char c = [Link](i);
int j = i;
// count run of same char
while (j < [Link]() && [Link](j) == c) j++;
int runLen = j - i;
if (runLen >= 2) {
[Link]('#'); // entire run → single '#'
} else {
[Link](c); // single char → keep as-is
}
i = j; // skip past the run
}

// ── Pass 2: collapse consecutive '#' into one '#' ──


StringBuilder result = new StringBuilder();
boolean prevHash = false;
for (char c : [Link]().toCharArray()) {
if (c == '#') {
if (!prevHash) [Link]('#');
prevHash = true;
} else {
[Link](c);
prevHash = false;
}
}
return [Link]();
}

public static void main(String[] args) {


[Link](replaceConsecutive("aabbcc")); // #
[Link](replaceConsecutive("aabbc")); // #c
[Link](replaceConsecutive("aaabbbccc"));// #
[Link](replaceConsecutive("abc")); // abc
[Link](replaceConsecutive("aabbXXcc")); // ###-> #
}
}

💡 Equivalent single-line Python (from platform screenshot): import re; return [Link](r'#+','#', [Link](r'(.)\\1+','#',s))
⚠ Java has no built-in backreference replace like Python's re — the two-pass loop above is the clean Java approach.

PR2 Remove Pairs, Count Remaining [Backend Q2]


Pattern: Frequency HashMap | Time: O(N) | Space: O(N) | ★ Confirmed on platform
Approach
Count frequency of each element. For each element, the number that cannot be paired = freq % 2. Sum all (freq
% 2) values to get the total remaining count.

Java Solution
import [Link].*;

public class RemovePairs {

public static int countRemaining(int N, int[] A) {


// Count frequency of each element
Map<Integer, Integer> freq = new HashMap<>();
for (int num : A) {
[Link](num, 1, Integer::sum);
}

// For each element: pairs removed = freq/2


// leftover = freq%2 (0 or 1)
int remaining = 0;
for (int count : [Link]()) {
remaining += count % 2; // 0 if even, 1 if odd
}
return remaining;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
int N = [Link]();
int[] A = new int[N];
for (int i = 0; i < N; i++) A[i] = [Link]();
[Link](countRemaining(N, A));
// Test: [1,2,3,1,2] -> 1
// Test: [1,1,2,2,3,3] -> 0
// Test: [1,1,1,2,3] -> 3 (1 appears 3 times: 1 leftover)
// Test: [1,2,3] -> 3 (all odd freq)
}
}

💡 Key formula: count % 2 tells you how many of that element remain unpaired (always 0 or 1). Sum these up for the
answer.
⚠ Even if an element appears 100 times, only 1 pair is NOT removed if freq is odd — the leftover 1 element stays. freq
% 2 handles this automatically.

PR3 Player Names and Teams — Age < 32 [Database Q1]


Pattern: INNER JOIN + WHERE | Time: O(N) | ★ Confirmed on platform — exact column aliases required
Approach
Join players table with teams table on team_id. Filter WHERE age < 32. Alias columns exactly as PLAYERNAME
and TEAMNAME (uppercase, no spaces) as shown in the platform output spec.

SQL Solution
-- Solution 1: INNER JOIN (players must have a team)
SELECT p.player_name AS PLAYERNAME,
t.team_name AS TEAMNAME
FROM players p
INNER JOIN teams t ON p.team_id = t.team_id
WHERE [Link] < 32;

-- Solution 2: If column name in players table is 'name' not 'player_name'


SELECT [Link] AS PLAYERNAME,
[Link] AS TEAMNAME
FROM players p
INNER JOIN teams t ON p.team_id = t.team_id
WHERE [Link] < 32;

-- Solution 3: If no JOIN is needed (denormalised table with both columns)


SELECT player_name AS PLAYERNAME,
team_name AS TEAMNAME
FROM players
WHERE age < 32;

Check the View Schema tab on the platform to confirm exact table and column names before writing your query.
⚠ ★ CRITICAL: The output column names must be EXACTLY 'PLAYERNAME' and 'TEAMNAME' (all caps, no space)
as shown in the platform screenshot. Wrong alias = wrong answer even if data is correct.
💡 Quick schema check: click 'View Schema' tab at the bottom-right of the query window on the platform before writing
any SQL.

Accenture 2026 Campus Hiring — Java Solutions Reference — For Internal Preparation Only

You might also like