Coding Round

Reverse a string without using StringBuilder.reverse().

Example

Loop from the end and also show the two-pointer swap on a char array:

public class Main {
    static String reverseLoop(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; i--) sb.append(s.charAt(i));
        return sb.toString();
    }

    static String reverseSwap(String s) {
        char[] c = s.toCharArray();
        for (int i = 0, j = c.length - 1; i < j; i++, j--) {
            char t = c[i]; c[i] = c[j]; c[j] = t;
        }
        return new String(c);
    }

    public static void main(String[] args) {
        System.out.println(reverseLoop("Selenium"));
        System.out.println(reverseSwap("ShopEase Automation"));
    }
}

Output

muineleS
noitamotuA esaEpohS

Count the occurrences of each character in a string.

Example

LinkedHashMap keeps the order of first appearance; spaces are skipped:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String text = "test automation";
        Map<Character, Integer> counts = new LinkedHashMap<>();
        for (char ch : text.toCharArray()) {
            if (ch == ' ') continue;
            counts.merge(ch, 1, Integer::sum);
        }
        System.out.println(counts);

        char most = Collections.max(counts.entrySet(), Map.Entry.comparingByValue()).getKey();
        System.out.println("Most frequent: " + most + " (" + counts.get(most) + " times)");
    }
}

Output

{t=4, e=1, s=1, a=2, u=1, o=2, m=1, i=1, n=1}
Most frequent: t (4 times)

Find duplicate product names in a list.

Example

A Set.add returns false when the element is already there:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> names = List.of("Boat Rockerz 450", "Mi TV 43", "JBL Tune 510BT",
                "Boat Rockerz 450", "USB-C Cable", "Mi TV 43", "Boat Rockerz 450");
        Set<String> seen = new HashSet<>();
        Set<String> duplicates = new LinkedHashSet<>();
        for (String n : names) {
            if (!seen.add(n)) duplicates.add(n);
        }
        System.out.println("Duplicates: " + duplicates);
        System.out.println("Unique count: " + seen.size() + " of " + names.size());
    }
}

Output

Duplicates: [Boat Rockerz 450, Mi TV 43]
Unique count: 4 of 7

Check whether a list of prices is sorted (as after "Sort by Price: Low to High").

Example

Compare each element with the next one, or compare with a sorted copy:

import java.util.*;

public class Main {
    static boolean isSortedAscending(List<Double> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i) > list.get(i + 1)) {
                System.out.println("  not sorted at index " + i + ": " + list.get(i) + " > " + list.get(i + 1));
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        List<Double> uiPrices = List.of(299.0, 499.0, 1299.0, 1499.0, 3299.0);
        List<Double> buggy = List.of(299.0, 1499.0, 499.0, 3299.0);
        System.out.println("uiPrices sorted? " + isSortedAscending(uiPrices));
        System.out.println("buggy sorted? " + isSortedAscending(buggy));

        List<String> names = List.of("apple watch", "Boat", "JBL", "mi band");
        List<String> copy = new ArrayList<>(names);
        copy.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println("names A-Z? " + names.equals(copy));
    }
}

Output

uiPrices sorted? true
  not sorted at index 1: 1499.0 > 499.0
buggy sorted? false
names A-Z? true

Extract the numeric value from a price string like "₹1,299.00".

Example

Remove everything except digits and the dot, or use a regex to find all numbers in a longer text:

import java.util.*;
import java.util.regex.*;

public class Main {
    static double price(String text) {
        return Double.parseDouble(text.replaceAll("[^0-9.]", ""));
    }

    public static void main(String[] args) {
        System.out.println(price("₹1,299.00"));
        System.out.println(price("Rs. 49,999"));   // trap: the dot in "Rs." gives 0.49999, use the regex below
        System.out.println(price("₹1,299.00") + price("₹200.50"));

        String offer = "Save ₹200 on orders above ₹1,999 (10% off)";
        Matcher m = Pattern.compile("\\d[\\d,]*(\\.\\d+)?").matcher(offer);
        List<Integer> numbers = new ArrayList<>();
        while (m.find()) numbers.add(Integer.parseInt(m.group().replace(",", "")));
        System.out.println("Numbers in offer text: " + numbers);

        Matcher rs = Pattern.compile("\\d[\\d,]*(\\.\\d+)?").matcher("Rs. 49,999");
        if (rs.find()) System.out.println("Rs. 49,999 with regex: " + Double.parseDouble(rs.group().replace(",", "")));
    }
}

Output

1299.0
0.49999
1499.5
Numbers in offer text: [200, 1999, 10]
Rs. 49,999 with regex: 49999.0

Compare expected and actual lists and report the differences.

Example

Typical use: menu items or dropdown options on the page vs the expected list from the requirement:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> expected = List.of("Electronics", "Fashion", "Home", "Books", "Toys");
        List<String> actual = List.of("Electronics", "Home", "Fashion", "Grocery", "Books");

        List<String> missing = new ArrayList<>(expected);
        missing.removeAll(actual);
        List<String> extra = new ArrayList<>(actual);
        extra.removeAll(expected);

        System.out.println("Same items, same order? " + expected.equals(actual));
        System.out.println("Same items, any order?  " + new HashSet<>(expected).equals(new HashSet<>(actual)));
        System.out.println("Missing on page: " + missing);
        System.out.println("Unexpected on page: " + extra);
    }
}

Output

Same items, same order? false
Same items, any order?  false
Missing on page: [Toys]
Unexpected on page: [Grocery]

Check whether a string is a palindrome (ignoring case and spaces).

Example

Two pointers from both ends, skipping non-letters:

public class Main {
    static boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            if (!Character.isLetterOrDigit(s.charAt(i))) { i++; continue; }
            if (!Character.isLetterOrDigit(s.charAt(j))) { j--; continue; }
            if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
            i++; j--;
        }
        return true;
    }

    public static void main(String[] args) {
        for (String s : new String[]{"Madam", "Nurses run", "Selenium", "A man, a plan, a canal: Panama", "12321"}) {
            System.out.println(s + " -> " + isPalindrome(s));
        }
    }
}

Output

Madam -> true
Nurses run -> true
Selenium -> false
A man, a plan, a canal: Panama -> true
12321 -> true

Find the second largest number in an array (without sorting).

Example

One pass with two variables; duplicates of the largest are ignored:

public class Main {
    static Integer secondLargest(int[] a) {
        Integer first = null, second = null;
        for (int x : a) {
            if (first == null || x > first) { second = first; first = x; }
            else if (x != first && (second == null || x > second)) second = x;
        }
        return second;
    }

    public static void main(String[] args) {
        System.out.println(secondLargest(new int[]{1499, 299, 4490, 3299, 4490}));
        System.out.println(secondLargest(new int[]{5, 5, 5}));
        System.out.println(secondLargest(new int[]{-3, -1, -7}));
    }
}

Output

3299
null
-3

Count the frequency of each word in a sentence.

Example

Lower-case, split on non-letters, count with streams; TreeMap gives sorted output:

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        String review = "Good sound, good bass. Battery is good but the app is slow; app crashes.";
        Map<String, Long> freq = Arrays.stream(review.toLowerCase().split("[^a-z]+"))
                .filter(w -> !w.isEmpty())
                .collect(Collectors.groupingBy(w -> w, TreeMap::new, Collectors.counting()));
        System.out.println(freq);

        freq.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
                .limit(2)
                .forEach(e -> System.out.println(e.getKey() + " = " + e.getValue()));
    }
}

Output

{app=2, bass=1, battery=1, but=1, crashes=1, good=3, is=2, slow=1, sound=1, the=1}
good = 3
app = 2

Count all links on a page and print their text and URL.

driver.get("https://shopease.example.com");
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());

for (WebElement link : links) {
    String text = link.getText().trim();
    String href = link.getDomAttribute("href");
    if (href != null && !href.isBlank()) {
        System.out.println((text.isEmpty() ? "(image link)" : text) + " -> " + href);
    }
}

Example

mvn test -Dtest=LinksTest

Example output

Total links: 64
Home -> /
Electronics -> /category/electronics
Fashion -> /category/fashion
(image link) -> /products/boat-rockerz-450
...

Find broken links on a page.

Collect every href, send an HTTP HEAD request to each, and report status codes of 400 or more. Selenium itself cannot read status codes, so use Java's HttpClient.

HttpClient http = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(5)).build();

List<String> urls = driver.findElements(By.tagName("a")).stream()
        .map(a -> a.getAttribute("href"))                  // absolute URL resolved by the browser
        .filter(u -> u != null && u.startsWith("http"))
        .distinct().toList();

List<String> broken = new ArrayList<>();
for (String url : urls) {
    HttpRequest req = HttpRequest.newBuilder(URI.create(url))
            .method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
    int status = http.send(req, HttpResponse.BodyHandlers.discarding()).statusCode();
    if (status >= 400) broken.add(status + " " + url);
}
System.out.println("Checked " + urls.size() + ", broken: " + broken);
Assert.assertTrue(broken.isEmpty(), "Broken links: " + broken);

Example

mvn test -Dtest=BrokenLinksTest

Example output

Checked 58, broken: [404 https://shopease.example.com/offers/diwali-2025, 500 https://shopease.example.com/blog/old-post]
[ERROR] BrokenLinksTest.noBrokenLinks:44 Broken links: [404 ..., 500 ...] expected [true] but found [false]

Read a dynamic web table and find the row for a given order.

<table id="orders">
  <thead><tr><th>Order</th><th>Date</th><th>Status</th><th>Total</th><th></th></tr></thead>
  <tbody>
    <tr><td>ORD-100482</td><td>12 Mar 2026</td><td>Delivered</td><td>₹1,499</td><td><a>Invoice</a></td></tr>
    <tr><td>ORD-100517</td><td>17 Mar 2026</td><td>Placed</td><td>₹4,490</td><td><a>Cancel</a></td></tr>
  </tbody>
</table>
// read headers once so the code survives column reordering
List<String> headers = driver.findElements(By.cssSelector("#orders thead th"))
        .stream().map(WebElement::getText).toList();
int statusCol = headers.indexOf("Status") + 1;          // XPath / nth-child are 1-based

List<WebElement> rows = driver.findElements(By.cssSelector("#orders tbody tr"));
System.out.println("Rows: " + rows.size());

String orderId = "ORD-100517";
WebElement row = driver.findElement(By.xpath("//table[@id='orders']//tr[td[1]='" + orderId + "']"));
String status = row.findElement(By.xpath("./td[" + statusCol + "]")).getText();
System.out.println(orderId + " status: " + status);
row.findElement(By.linkText("Cancel")).click();

Example

output

Example output

Rows: 2
ORD-100517 status: Placed

Select a date in a date picker.

Two approaches: type into the input if it accepts text, or navigate the calendar until the right month is shown and click the day.

public void pickDate(LocalDate target) {
    driver.findElement(By.id("delivery-date")).click();
    DateTimeFormatter header = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
    String wanted = target.format(header);                         // "April 2026"

    for (int i = 0; i < 24 && !driver.findElement(By.cssSelector(".calendar .month-title"))
            .getText().equals(wanted); i++) {
        driver.findElement(By.cssSelector(".calendar .next")).click();
    }
    driver.findElement(By.xpath("//div[@class='calendar']//td[not(contains(@class,'disabled'))]"
            + "/button[text()='" + target.getDayOfMonth() + "']")).click();
}

pickDate(LocalDate.of(2026, 4, 5));
System.out.println(driver.findElement(By.id("delivery-date")).getDomProperty("value"));

Example

output

Example output

05/04/2026

Tip: If the input is a plain <input type="date">, skip the calendar: sendKeys("05-04-2026") in the format of the browser locale, or set the value with JavaScript and fire a change event.