<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abhishek Pathak on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Pathak on Medium]]></description>
        <link>https://medium.com/@myofficework000?source=rss-67863a1cb6b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q_NDj-61q3Hy_BeP4mKyAQ.png</url>
            <title>Stories by Abhishek Pathak on Medium</title>
            <link>https://medium.com/@myofficework000?source=rss-67863a1cb6b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:23:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@myofficework000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LeetCode Patterns to Crack FAANG]]></title>
            <link>https://medium.com/@myofficework000/leetcode-patterns-to-crack-faang-89378195dc90?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/89378195dc90</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[faang]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 19:38:32 GMT</pubDate>
            <atom:updated>2026-09-10T19:38:32.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MufD92svIA_rhoEkBWpAHQ.png" /></figure><h3>Preparing for a FAANG interview does not mean solving 500 random LeetCode problems.</h3><p>The smarter approach is to understand the most frequently used problem-solving patterns and practise a carefully selected set of questions under each one.</p><p>Most coding interview problems are variations or combinations of a few fundamental patterns. Once you learn how to identify these patterns, unfamiliar questions become significantly easier to approach.</p><p>My preparation strategy is simple:</p><ul><li>Learn the core concept behind each pattern.</li><li>Start with easy problems to build confidence.</li><li>Progress gradually to medium and hard problems.</li><li>Understand the time and space complexity of every solution.</li><li>Revisit problems until I can solve them without hints.</li><li>Practise explaining my approach before writing code.</li><li>Complete timed mock interviews regularly.</li></ul><p>Here are the LeetCode patterns and problems I will focus on while preparing for Google and other FAANG interviews.</p><h3>1. Arrays and Hashing</h3><p>Arrays and hashing are the foundation of coding interviews. Hash maps and hash sets help reduce lookup time and often turn an inefficient solution into an optimal one.</p><p>Focus on frequency counting, duplicate detection, grouping, indexing and constant-time lookup.</p><ol><li><a href="https://leetcode.com/problems/contains-duplicate/">Contains Duplicate</a></li><li><a href="https://leetcode.com/problems/valid-anagram/">Valid Anagram</a></li><li><a href="https://leetcode.com/problems/two-sum/">Two Sum</a></li><li><a href="https://leetcode.com/problems/group-anagrams/">Group Anagrams</a></li><li><a href="https://leetcode.com/problems/longest-consecutive-sequence/">Longest Consecutive Sequence</a></li><li><a href="https://leetcode.com/problems/valid-sudoku/">Valid Sudoku</a></li></ol><h3>2. Two Pointers</h3><p>The two-pointer technique is useful when working with sorted arrays, strings, pairs or ranges.</p><p>Instead of using nested loops, two pointers can often reduce the time complexity from O(n²) to O(n).</p><ol><li><a href="https://leetcode.com/problems/valid-palindrome/">Valid Palindrome</a></li><li><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/">Remove Duplicates from Sorted Array</a></li><li><a href="https://leetcode.com/problems/merge-sorted-array/">Merge Sorted Array</a></li><li><a href="https://leetcode.com/problems/container-with-most-water/">Container With Most Water</a></li><li><a href="https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/">Two Sum II — Input Array Is Sorted</a></li><li><a href="https://leetcode.com/problems/3sum/">3Sum</a></li></ol><h3>3. Stack</h3><p>A stack follows the Last-In, First-Out principle. It is frequently used for parentheses validation, expression evaluation, monotonic-stack problems and maintaining processing order.</p><ol><li><a href="https://leetcode.com/problems/valid-parentheses/">Valid Parentheses</a></li><li><a href="https://leetcode.com/problems/next-greater-element-i/">Next Greater Element I</a></li><li><a href="https://leetcode.com/problems/remove-outermost-parentheses/">Remove Outermost Parentheses</a></li><li><a href="https://leetcode.com/problems/min-stack/">Min Stack</a></li><li><a href="https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/">Minimum Add to Make Parentheses Valid</a></li><li><a href="https://leetcode.com/problems/basic-calculator-ii/">Basic Calculator II</a></li></ol><h3>4. Binary Search</h3><p>Binary search is not limited to finding an element in a sorted array. It can also be used to search for boundaries, rotated values, peaks and the smallest or largest valid answer.</p><p>The key is identifying whether the search space can be divided based on a condition.</p><ol><li><a href="https://leetcode.com/problems/binary-search/">Binary Search</a></li><li><a href="https://leetcode.com/problems/search-insert-position/">Search Insert Position</a></li><li><a href="https://leetcode.com/problems/kth-missing-positive-number/">Kth Missing Positive Number</a></li><li><a href="https://leetcode.com/problems/find-peak-element/">Find Peak Element</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">Search in Rotated Sorted Array</a></li><li><a href="https://leetcode.com/problems/search-a-2d-matrix/">Search a 2D Matrix</a></li></ol><h3>5. Sliding Window</h3><p>Sliding window is commonly used for contiguous subarrays and substrings.</p><p>It allows us to maintain a valid range while avoiding repeated calculations, making it ideal for maximum, minimum, frequency and length-based problems.</p><ol><li><a href="https://leetcode.com/problems/maximum-average-subarray-i/">Maximum Average Subarray I</a></li><li><a href="https://leetcode.com/problems/find-the-k-beauty-of-a-number/">Find the K-Beauty of a Number</a></li><li><a href="https://leetcode.com/problems/contains-duplicate-ii/">Contains Duplicate II</a></li><li><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">Longest Substring Without Repeating Characters</a></li><li><a href="https://leetcode.com/problems/subarray-product-less-than-k/">Subarray Product Less Than K</a></li><li><a href="https://leetcode.com/problems/longest-repeating-character-replacement/">Longest Repeating Character Replacement</a></li></ol><h3>6. Linked List</h3><p>Linked-list questions test pointer manipulation, traversal and memory-efficient problem-solving.</p><p>The most important techniques include slow and fast pointers, reversing links, merging nodes and using dummy nodes.</p><ol><li><a href="https://leetcode.com/problems/merge-two-sorted-lists/">Merge Two Sorted Lists</a></li><li><a href="https://leetcode.com/problems/reverse-linked-list/">Reverse Linked List</a></li><li><a href="https://leetcode.com/problems/middle-of-the-linked-list/">Middle of the Linked List</a></li><li><a href="https://leetcode.com/problems/add-two-numbers/">Add Two Numbers</a></li><li><a href="https://leetcode.com/problems/lru-cache/">LRU Cache</a></li><li><a href="https://leetcode.com/problems/reorder-list/">Reorder List</a></li></ol><h3>7. Trees</h3><p>Tree problems are extremely common in FAANG interviews.</p><p>You should be comfortable with recursion, depth-first search, breadth-first search, tree height, subtree comparison and binary-search-tree properties.</p><ol><li><a href="https://leetcode.com/problems/same-tree/">Same Tree</a></li><li><a href="https://leetcode.com/problems/maximum-depth-of-binary-tree/">Maximum Depth of Binary Tree</a></li><li><a href="https://leetcode.com/problems/diameter-of-binary-tree/">Diameter of Binary Tree</a></li><li><a href="https://leetcode.com/problems/binary-tree-level-order-traversal/">Binary Tree Level Order Traversal</a></li><li><a href="https://leetcode.com/problems/validate-binary-search-tree/">Validate Binary Search Tree</a></li><li><a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/">Lowest Common Ancestor of a Binary Tree</a></li></ol><h3>8. Trie</h3><p>A trie is designed for efficiently storing and searching strings by prefix.</p><p>It is especially useful for autocomplete, dictionaries, prefix matching and word-search features.</p><ol><li><a href="https://leetcode.com/problems/longest-common-prefix/">Longest Common Prefix</a></li><li><a href="https://leetcode.com/problems/count-prefix-and-suffix-pairs-i/">Count Prefix and Suffix Pairs I</a></li><li><a href="https://leetcode.com/problems/implement-trie-prefix-tree/">Implement Trie — Prefix Tree</a></li><li><a href="https://leetcode.com/problems/design-add-and-search-words-data-structure/">Design Add and Search Words Data Structure</a></li><li><a href="https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix/">Find the Length of the Longest Common Prefix</a></li></ol><h3>9. Backtracking</h3><p>Backtracking helps explore every possible valid decision while abandoning paths that cannot produce the required result.</p><p>This pattern is commonly used for combinations, permutations, subsets and path-generation problems.</p><ol><li><a href="https://leetcode.com/problems/binary-tree-paths/">Binary Tree Paths</a></li><li><a href="https://leetcode.com/problems/binary-watch/">Binary Watch</a></li><li><a href="https://leetcode.com/problems/sum-of-all-subset-xor-totals/">Sum of All Subset XOR Totals</a></li><li><a href="https://leetcode.com/problems/subsets/">Subsets</a></li><li><a href="https://leetcode.com/problems/permutations/">Permutations</a></li><li><a href="https://leetcode.com/problems/combination-sum/">Combination Sum</a></li></ol><h3>10. Heap or Priority Queue</h3><p>A heap is useful when a problem asks for the smallest, largest, nearest or highest-priority elements.</p><p>This pattern frequently appears in top-K problems, task scheduling, streaming data and ranking systems.</p><ol><li><a href="https://leetcode.com/problems/last-stone-weight/">Last Stone Weight</a></li><li><a href="https://leetcode.com/problems/kth-largest-element-in-a-stream/">Kth Largest Element in a Stream</a></li><li><a href="https://leetcode.com/problems/relative-ranks/">Relative Ranks</a></li><li><a href="https://leetcode.com/problems/k-closest-points-to-origin/">K Closest Points to Origin</a></li><li><a href="https://leetcode.com/problems/kth-largest-element-in-an-array/">Kth Largest Element in an Array</a></li><li><a href="https://leetcode.com/problems/task-scheduler/">Task Scheduler</a></li></ol><h3>11. Graphs</h3><p>Graph questions test your ability to model relationships between connected elements.</p><p>The essential techniques are breadth-first search, depth-first search, visited-node tracking, connected components and shortest-path traversal.</p><ol><li><a href="https://leetcode.com/problems/find-center-of-star-graph/">Find Center of Star Graph</a></li><li><a href="https://leetcode.com/problems/find-the-town-judge/">Find the Town Judge</a></li><li><a href="https://leetcode.com/problems/find-if-path-exists-in-graph/">Find if Path Exists in Graph</a></li><li><a href="https://leetcode.com/problems/number-of-islands/">Number of Islands</a></li><li><a href="https://leetcode.com/problems/rotting-oranges/">Rotting Oranges</a></li></ol><h3>12. Intervals</h3><p>Interval problems usually involve overlapping ranges, schedules, meetings or time slots.</p><p>The most important first step is often sorting intervals by their starting or ending values.</p><ol><li><a href="https://leetcode.com/problems/insert-interval/">Insert Interval</a></li><li><a href="https://leetcode.com/problems/merge-intervals/">Merge Intervals</a></li><li><a href="https://leetcode.com/problems/non-overlapping-intervals/">Non-overlapping Intervals</a></li></ol><h3>13. Greedy and Dynamic Programming</h3><p>Greedy algorithms choose the best available decision at every step, while dynamic programming stores previously calculated results to avoid repeated work.</p><p>The most important skill is learning how to determine whether a locally optimal choice can produce the globally optimal result.</p><ol><li><a href="https://leetcode.com/problems/jump-game/">Jump Game</a></li><li><a href="https://leetcode.com/problems/jump-game-ii/">Jump Game II</a></li><li><a href="https://leetcode.com/problems/gas-station/">Gas Station</a></li></ol><h3>14. Advanced Graphs</h3><p>Advanced graph problems involve weighted edges, shortest paths and minimum spanning trees.</p><p>These questions require familiarity with algorithms such as Dijkstra’s algorithm, Bellman–Ford, Prim’s algorithm and Kruskal’s algorithm.</p><ol><li><a href="https://leetcode.com/problems/cheapest-flights-within-k-stops/">Cheapest Flights Within K Stops</a></li><li><a href="https://leetcode.com/problems/network-delay-time/">Network Delay Time</a></li><li><a href="https://leetcode.com/problems/min-cost-to-connect-all-points/">Min Cost to Connect All Points</a></li></ol><h3>How to Follow This Roadmap</h3><p>Simply solving every question once is not enough. Use the following approach for each problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbgO-MM8P1mhGcPhhFr0ww.png" /></figure><h3>Step 1: Understand the requirement</h3><p>Identify the input, expected output, constraints and edge cases before writing code.</p><h3>Step 2: Find the brute-force solution</h3><p>Start with the simplest possible approach. This demonstrates that you understand the problem before attempting optimization.</p><h3>Step 3: Identify the pattern</h3><p>Ask yourself:</p><ul><li>Is the input sorted?</li><li>Does the problem involve a contiguous range?</li><li>Do I need fast lookup or frequency counting?</li><li>Am I exploring every possible combination?</li><li>Is this a shortest-path or connected-component problem?</li><li>Can a previous result help calculate the next result?</li></ul><h3>Step 4: Write the optimized solution</h3><p>Explain why the optimized approach works before implementing it.</p><h3>Step 5: Analyse complexity</h3><p>Always calculate:</p><ul><li>Time complexity</li><li>Space complexity</li><li>Cost of any sorting or additional data structure</li></ul><h3>Step 6: Test edge cases</h3><p>Test the solution against:</p><ul><li>Empty input</li><li>Single-element input</li><li>Duplicate values</li><li>Negative values</li><li>Already sorted input</li><li>Maximum input size</li></ul><h3>Step 7: Revisit the problem</h3><p>Use a revision cycle:</p><ul><li>Solve it today.</li><li>Repeat it after three days.</li><li>Repeat it after one week.</li><li>Solve it again during a timed mock interview.</li></ul><h3>A Practical 14-Week FAANG Preparation Plan</h3><p>Follow one pattern every week:</p><ul><li>Week 1: Arrays and Hashing</li><li>Week 2: Two Pointers</li><li>Week 3: Stack</li><li>Week 4: Binary Search</li><li>Week 5: Sliding Window</li><li>Week 6: Linked List</li><li>Week 7: Trees</li><li>Week 8: Trie</li><li>Week 9: Backtracking</li><li>Week 10: Heap</li><li>Week 11: Graphs</li><li>Week 12: Intervals</li><li>Week 13: Greedy and Dynamic Programming</li><li>Week 14: Advanced Graphs and Mock Interviews</li></ul><p>For every pattern, focus on recognising why it works — not merely memorising the final code.</p><h3>Final Thoughts</h3><p>Getting into FAANG is not about the number of problems you solve. It is about the quality of your preparation and your ability to recognise patterns under pressure.</p><p>Do not blindly grind hundreds of random questions.</p><p>Master these 14 patterns, understand their common variations, practise communicating your thought process and revise consistently. This approach will not guarantee an offer, but it can make your interview preparation far more focused, structured and effective.</p><p>If you are preparing for a FAANG interview in 2026, save this roadmap and start with the first pattern today.</p><blockquote>Which pattern are you currently practising?</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89378195dc90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing Android ViewModel with Kotlin StateFlow, MockK, Coroutines, and Turbine]]></title>
            <link>https://medium.com/@myofficework000/unit-testing-android-viewmodel-with-kotlin-stateflow-mockk-coroutines-and-turbine-6143ea982ab6?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6143ea982ab6</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[mockk]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 19:50:28 GMT</pubDate>
            <atom:updated>2026-06-26T19:50:28.416Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unit Testing Series #6</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYdqtmZFfsbKaSaZ933PjA.png" /></figure><p>In this article, we will learn how to unit test an Android ViewModel that uses Kotlin StateFlow.</p><p><a href="https://medium.com/@myofficework000/unit-testing-series-5-e356e62bc44c">In the previous example</a>, we tested a ViewModel using LiveData. With LiveData, we usually attach an observer and verify observer calls. But when we use Kotlin Flow or StateFlow, the testing approach is different.</p><p>Here, we will test a ViewModel that exposes UI state using StateFlow.</p><p>We will cover two approaches:</p><ol><li>Testing StateFlow without Turbine</li><li>Testing StateFlow with Turbine</li></ol><p>Turbine is not mandatory, but it makes Flow testing cleaner when we want to verify multiple emissions in sequence.</p><p>For example:</p><pre>Init -&gt; Loading -&gt; Success</pre><p>Without Turbine, we can still test the final value of StateFlow.</p><p>With Turbine, we can test the complete emission order clearly.</p><h3>What We Are Going to Test</h3><p>We have a currency exchange ViewModel.</p><p>The ViewModel calls a use case and updates the UI state based on the response.</p><p>The UI state can be:</p><pre>Init<br>Loading<br>Success<br>Error</pre><h3>AppState</h3><pre>sealed class AppState {<br>data class Success(<br>        val result: ApiResponse<br>    ) : AppState()<br>    data class Error(<br>        val msg: String<br>    ) : AppState()<br>    object Init : AppState()<br>    object Loading : AppState()<br>}</pre><h3>ViewModel</h3><pre>@HiltViewModel<br>class CurrencyViewModel @Inject constructor(<br>    private val getCurrencyRateUseCase: GetCurrencyRateUseCase<br>) : ViewModel() {<br>-<br>  private val _appState = MutableStateFlow&lt;AppState&gt;(AppState.Init)<br>    val appState: StateFlow&lt;AppState&gt; = _appState.asStateFlow()<br>    fun retrieveCurrencyRate(code: String) {<br>        viewModelScope.launch {<br>            _appState.value = AppState.Loading<br>            val response: Response&lt;ApiResponse&gt;? = getCurrencyRateUseCase(code)<br>            if (response != null) {<br>                if (response.isSuccessful &amp;&amp; response.body() != null) {<br>                    _appState.value = AppState.Success(response.body()!!)<br>                } else {<br>                    _appState.value =<br>                        AppState.Error(&quot;Something went wrong while fetching data&quot;)<br>                }<br>            } else {<br>                _appState.value = AppState.Error(&quot;Something is not working&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>UseCase</h3><pre>class GetCurrencyRateUseCase @Inject constructor(<br>    private val repo: CurrencyExRepository<br>) {<br>    suspend operator fun invoke(code: String): Response&lt;ApiResponse&gt;? {<br>        return repo.getCurrencyRate(code)<br>    }<br>}</pre><h3>Repository</h3><pre>class CurrencyExRepositoryImpl @Inject constructor(<br>    private val apiService: ApiService<br>) : CurrencyExRepository {<br>    override suspend fun getCurrencyRate(code: String): Response&lt;ApiResponse&gt;? {<br>        return try {<br>            val response = apiService.getExchangeRate(code)<br>            if (response != null &amp;&amp; response.isSuccessful &amp;&amp; response.body() != null) {<br>                response<br>            } else {<br>                null<br>            }<br>        } catch (ex: Exception) {<br>            null<br>        }<br>    }<br>}</pre><p>In this article, we are testing only the ViewModel.</p><p>So we will mock the GetCurrencyRateUseCase.</p><p>We are not testing the actual API call here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FWxDGnOwjJX7LsFp__UQQ.png" /></figure><h3>Required Dependencies</h3><pre>dependencies {<br>    // JUnit<br>    testImplementation(&quot;junit:junit:4.13.2&quot;)<br>    // MockK<br>    testImplementation(&quot;io.mockk:mockk:1.14.11&quot;)<br>    // Coroutine testing<br>    testImplementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2&quot;)<br>    // Turbine for Flow testing<br>    testImplementation(&quot;app.cash.turbine:turbine:1.2.1&quot;)<br>}</pre><h3>Test Cases Covered</h3><p>Before writing the unit tests, let’s define the scenarios clearly.</p><h3>Test Case 1</h3><p><strong>GIVEN</strong> ViewModel is created<br><strong>WHEN</strong> appState is observed<br><strong>THEN</strong> initial state should be Init</p><h3>Test Case 2</h3><p><strong>GIVEN</strong> use case returns success response with valid body<br><strong>WHEN</strong> retrieveCurrencyRate() is invoked<br><strong>THEN</strong> appState should emit Loading and then Success</p><h3>Test Case 3</h3><p><strong>GIVEN</strong> use case returns success response with null body<br><strong>WHEN</strong> retrieveCurrencyRate() is invoked<br><strong>THEN</strong> appState should emit Loading and then Error</p><h3>Test Case 4</h3><p><strong>GIVEN</strong> use case returns API error response<br><strong>WHEN</strong> retrieveCurrencyRate() is invoked<br><strong>THEN</strong> appState should emit Loading and then Error</p><h3>Test Case 5</h3><p><strong>GIVEN</strong> use case returns null response<br><strong>WHEN</strong> retrieveCurrencyRate() is invoked<br><strong>THEN</strong> appState should emit Loading and then Error</p><h3>MainDispatcherRule</h3><p>ViewModel uses viewModelScope, and viewModelScope runs on the Main dispatcher.</p><p>In local unit tests, we do not have the Android Main dispatcher available. So we need to replace it with a test dispatcher.</p><pre>@OptIn(ExperimentalCoroutinesApi::class)<br>class MainDispatcherRule(<br>    val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()<br>) : TestWatcher() {<br><br>override fun starting(description: Description) {<br>        Dispatchers.setMain(testDispatcher)<br>    }<br>    override fun finished(description: Description) {<br>        Dispatchers.resetMain()<br>    }<br></pre><h3>Approach 1: Testing StateFlow Without Turbine</h3><p>First, let’s test StateFlow without using Turbine.</p><p>In this approach, we will mainly check the final value of StateFlow using:</p><pre>viewModel.appState.value</pre><p>This approach is simple and useful when we only care about the final state.</p><h3>Test 1: Initial State</h3><pre>@Test<br>fun `GIVEN viewmodel created WHEN appState checked THEN initial state should be Init`() {<br>    // GIVEN<br>    // ViewModel is created in setup<br>    // WHEN<br>    val actualState = viewModel.appState.value<br>    // THEN<br>    assertEquals(AppState.Init, actualState)<br>}</pre><h3>Test 2: Success Response with Body</h3><pre>@Test<br>fun `GIVEN success response with body WHEN retrieveCurrencyRate invoked THEN state should be Success`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br>    val apiResponse = ApiResponse(<br>        // Add fake response data here based on your model<br>    )<br>    val responseFromApi = Response.success(apiResponse)<br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns responseFromApi<br>    // WHEN<br>    viewModel.retrieveCurrencyRate(currencyCode)<br>    advanceUntilIdle()<br>    // THEN<br>    coVerify(exactly = 1) {<br>        getCurrencyRateUseCase(currencyCode)<br>    }<br>    assertEquals(<br>        AppState.Success(apiResponse),<br>        viewModel.appState.value<br>    )<br>}</pre><h3>Test 3: Success Response with Null Body</h3><pre>@Test<br>fun `GIVEN success response with null body WHEN retrieveCurrencyRate invoked THEN state should be Error`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>    val responseFromApi = Response.success&lt;ApiResponse&gt;(null)<br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns responseFromApi<br>    // WHEN<br>    viewModel.retrieveCurrencyRate(currencyCode)<br>    advanceUntilIdle()<br>    // THEN<br>    coVerify(exactly = 1) {<br>        getCurrencyRateUseCase(currencyCode)<br>    }<br>    assertEquals(<br>        AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>        viewModel.appState.value<br>    )<br>}</pre><h3>Test 4: API Error Response</h3><pre>@Test<br>fun `GIVEN api error response WHEN retrieveCurrencyRate invoked THEN state should be Error`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>    val responseFromApi = Response.error&lt;ApiResponse&gt;(<br>        500,<br>        &quot;Internal Server Error&quot;.toResponseBody(&quot;text/plain&quot;.toMediaType())<br>    )<br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns responseFromApi<br>    // WHEN<br>    viewModel.retrieveCurrencyRate(currencyCode)<br>    advanceUntilIdle()<br>    // THEN<br>    coVerify(exactly = 1) {<br>        getCurrencyRateUseCase(currencyCode)<br>    }<br>    assertEquals(<br>        AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>        viewModel.appState.value<br>    )<br>}</pre><h3>Test 5: Null Response</h3><pre>@Test<br>fun `GIVEN null response WHEN retrieveCurrencyRate invoked THEN state should be Error`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns null<br>    // WHEN<br>    viewModel.retrieveCurrencyRate(currencyCode)<br>    advanceUntilIdle()<br>    // THEN<br>    coVerify(exactly = 1) {<br>        getCurrencyRateUseCase(currencyCode)<br>    }<br>    assertEquals(<br>        AppState.Error(&quot;Something is not working&quot;),<br>        viewModel.appState.value<br>    )<br>}</pre><h3>Full Test Class Without Turbine</h3><pre>@OptIn(ExperimentalCoroutinesApi::class)<br>class CurrencyViewModelWithoutTurbineTest {<br><br>@get:Rule<br>    val mainDispatcherRule = MainDispatcherRule()<br>    private val getCurrencyRateUseCase = mockk&lt;GetCurrencyRateUseCase&gt;()<br>    private lateinit var viewModel: CurrencyViewModel<br>    @Before<br>    fun setup() {<br>        viewModel = CurrencyViewModel(<br>            getCurrencyRateUseCase = getCurrencyRateUseCase<br>        )<br>    }<br>    @Test<br>    fun `GIVEN viewmodel created WHEN appState checked THEN initial state should be Init`() {<br>        // GIVEN<br>        // ViewModel is created in setup<br>        // WHEN<br>        val actualState = viewModel.appState.value<br>        // THEN<br>        assertEquals(AppState.Init, actualState)<br>    }<br>    @Test<br>    fun `GIVEN success response with body WHEN retrieveCurrencyRate invoked THEN state should be Success`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        val apiResponse = ApiResponse(<br>            // Add fake response data here based on your model<br>        )<br>        val responseFromApi = Response.success(apiResponse)<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns responseFromApi<br>        // WHEN<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        advanceUntilIdle()<br>        // THEN<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        assertEquals(<br>            AppState.Success(apiResponse),<br>            viewModel.appState.value<br>        )<br>    }<br>    @Test<br>    fun `GIVEN success response with null body WHEN retrieveCurrencyRate invoked THEN state should be Error`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        val responseFromApi = Response.success&lt;ApiResponse&gt;(null)<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns responseFromApi<br>        // WHEN<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        advanceUntilIdle()<br>        // THEN<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        assertEquals(<br>            AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>            viewModel.appState.value<br>        )<br>    }<br>    @Test<br>    fun `GIVEN api error response WHEN retrieveCurrencyRate invoked THEN state should be Error`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        val responseFromApi = Response.error&lt;ApiResponse&gt;(<br>            500,<br>            &quot;Internal Server Error&quot;.toResponseBody(&quot;text/plain&quot;.toMediaType())<br>        )<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns responseFromApi<br>        // WHEN<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        advanceUntilIdle()<br>        // THEN<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        assertEquals(<br>            AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>            viewModel.appState.value<br>        )<br>    }<br>    @Test<br>    fun `GIVEN null response WHEN retrieveCurrencyRate invoked THEN state should be Error`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns null<br>        // WHEN<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        advanceUntilIdle()<br>        // THEN<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        assertEquals(<br>            AppState.Error(&quot;Something is not working&quot;),<br>            viewModel.appState.value<br>        )<br>    }<br>}</pre><h3>Approach 2: Testing StateFlow With Turbine</h3><p>Now let’s test the same ViewModel using Turbine.</p><p>Turbine provides a simple API to collect Flow emissions one by one.</p><p>Example:</p><pre>viewModel.appState.test {<br>    assertEquals(AppState.Init, awaitItem())<br>    assertEquals(AppState.Loading, awaitItem())<br>    assertEquals(AppState.Success(apiResponse), awaitItem())<br>}</pre><p>This is useful when we want to verify the complete state sequence.</p><h3>Test 1: Initial State</h3><pre>@Test<br>fun `GIVEN viewmodel created WHEN appState collected THEN initial state should be Init`() = runTest {<br>    // GIVEN<br>    // ViewModel is created in setup<br>    // WHEN + THEN<br>    viewModel.appState.test {<br>        assertEquals(AppState.Init, awaitItem())<br>        cancelAndIgnoreRemainingEvents()<br>    }<br>}</pre><h3>Test 2: Success Response with Body</h3><pre>@Test<br>fun `GIVEN success response with body WHEN retrieveCurrencyRate invoked THEN emit Loading and Success`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>    val apiResponse = ApiResponse(<br>        // Add fake response data here based on your model<br>    )<br>    val responseFromApi = Response.success(apiResponse)<br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns responseFromApi<br>    // WHEN + THEN<br>    viewModel.appState.test {<br>        assertEquals(AppState.Init, awaitItem())<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        assertEquals(AppState.Loading, awaitItem())<br>        assertEquals(<br>            AppState.Success(apiResponse),<br>            awaitItem()<br>        )<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        cancelAndIgnoreRemainingEvents()<br>    }<br>}</pre><h3>Test 3: Success Response with Null Body</h3><pre>@Test<br>fun `GIVEN success response with null body WHEN retrieveCurrencyRate invoked THEN emit Loading and Error`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>    val responseFromApi = Response.success&lt;ApiResponse&gt;(null)<br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns responseFromApi<br>    // WHEN + THEN<br>    viewModel.appState.test {<br>        assertEquals(AppState.Init, awaitItem())<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        assertEquals(AppState.Loading, awaitItem())<br>        assertEquals(<br>            AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>            awaitItem()<br>        )<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        cancelAndIgnoreRemainingEvents()<br>    }<br>}</pre><h3>Test 4: API Error Response</h3><pre>@Test<br>fun `GIVEN api error response WHEN retrieveCurrencyRate invoked THEN emit Loading and Error`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>    val responseFromApi = Response.error&lt;ApiResponse&gt;(<br>        500,<br>        &quot;Internal Server Error&quot;.toResponseBody(&quot;text/plain&quot;.toMediaType())<br>    )<br>    coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns responseFromApi<br>    // WHEN + THEN<br>    viewModel.appState.test {<br>        assertEquals(AppState.Init, awaitItem())<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        assertEquals(AppState.Loading, awaitItem())<br>        assertEquals(<br>            AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>            awaitItem()<br>        )<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        cancelAndIgnoreRemainingEvents()<br>    }<br>}</pre><h3>Test 5: Null Response</h3><pre>@Test<br>fun `GIVEN null response WHEN retrieveCurrencyRate invoked THEN emit Loading and Error`() = runTest {<br>    // GIVEN<br>    val currencyCode = &quot;USD&quot;<br><br>   coEvery {<br>        getCurrencyRateUseCase(currencyCode)<br>    } returns null<br>    // WHEN + THEN<br>    viewModel.appState.test {<br>        assertEquals(AppState.Init, awaitItem())<br>        viewModel.retrieveCurrencyRate(currencyCode)<br>        assertEquals(AppState.Loading, awaitItem())<br>        assertEquals(<br>            AppState.Error(&quot;Something is not working&quot;),<br>            awaitItem()<br>        )<br>        coVerify(exactly = 1) {<br>            getCurrencyRateUseCase(currencyCode)<br>        }<br>        cancelAndIgnoreRemainingEvents()<br>    }<br>}</pre><h3>Full Test Class With Turbine</h3><pre>@OptIn(ExperimentalCoroutinesApi::class)<br>class CurrencyViewModelWithTurbineTest {<br><br>@get:Rule<br>    val mainDispatcherRule = MainDispatcherRule()<br>    private val getCurrencyRateUseCase = mockk&lt;GetCurrencyRateUseCase&gt;()<br>    private lateinit var viewModel: CurrencyViewModel<br>    @Before<br>    fun setup() {<br>        viewModel = CurrencyViewModel(<br>            getCurrencyRateUseCase = getCurrencyRateUseCase<br>        )<br>    }<br>    @Test<br>    fun `GIVEN viewmodel created WHEN appState collected THEN initial state should be Init`() = runTest {<br>        // GIVEN<br>        // ViewModel is created in setup<br>        // WHEN + THEN<br>        viewModel.appState.test {<br>            assertEquals(AppState.Init, awaitItem())<br>            cancelAndIgnoreRemainingEvents()<br>        }<br>    }<br>    @Test<br>    fun `GIVEN success response with body WHEN retrieveCurrencyRate invoked THEN emit Loading and Success`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        val apiResponse = ApiResponse(<br>            // Add fake response data here based on your model<br>        )<br>        val responseFromApi = Response.success(apiResponse)<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns responseFromApi<br>        // WHEN + THEN<br>        viewModel.appState.test {<br>            assertEquals(AppState.Init, awaitItem())<br>            viewModel.retrieveCurrencyRate(currencyCode)<br>            assertEquals(AppState.Loading, awaitItem())<br>            assertEquals(<br>                AppState.Success(apiResponse),<br>                awaitItem()<br>            )<br>            coVerify(exactly = 1) {<br>                getCurrencyRateUseCase(currencyCode)<br>            }<br>            cancelAndIgnoreRemainingEvents()<br>        }<br>    }<br>    @Test<br>    fun `GIVEN success response with null body WHEN retrieveCurrencyRate invoked THEN emit Loading and Error`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        val responseFromApi = Response.success&lt;ApiResponse&gt;(null)<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns responseFromApi<br>        // WHEN + THEN<br>        viewModel.appState.test {<br>            assertEquals(AppState.Init, awaitItem())<br>            viewModel.retrieveCurrencyRate(currencyCode)<br>            assertEquals(AppState.Loading, awaitItem())<br>            assertEquals(<br>                AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>                awaitItem()<br>            )<br>            coVerify(exactly = 1) {<br>                getCurrencyRateUseCase(currencyCode)<br>            }<br>            cancelAndIgnoreRemainingEvents()<br>        }<br>    }<br>    @Test<br>    fun `GIVEN api error response WHEN retrieveCurrencyRate invoked THEN emit Loading and Error`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        val responseFromApi = Response.error&lt;ApiResponse&gt;(<br>            500,<br>            &quot;Internal Server Error&quot;.toResponseBody(&quot;text/plain&quot;.toMediaType())<br>        )<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns responseFromApi<br>        // WHEN + THEN<br>        viewModel.appState.test {<br>            assertEquals(AppState.Init, awaitItem())<br>            viewModel.retrieveCurrencyRate(currencyCode)<br>            assertEquals(AppState.Loading, awaitItem())<br>            assertEquals(<br>                AppState.Error(&quot;Something went wrong while fetching data&quot;),<br>                awaitItem()<br>            )<br>            coVerify(exactly = 1) {<br>                getCurrencyRateUseCase(currencyCode)<br>            }<br>            cancelAndIgnoreRemainingEvents()<br>        }<br>    }<br>    @Test<br>    fun `GIVEN null response WHEN retrieveCurrencyRate invoked THEN emit Loading and Error`() = runTest {<br>        // GIVEN<br>        val currencyCode = &quot;USD&quot;<br>        coEvery {<br>            getCurrencyRateUseCase(currencyCode)<br>        } returns null<br>        // WHEN + THEN<br>        viewModel.appState.test {<br>            assertEquals(AppState.Init, awaitItem())<br>            viewModel.retrieveCurrencyRate(currencyCode)<br>            assertEquals(AppState.Loading, awaitItem())<br>            assertEquals(<br>                AppState.Error(&quot;Something is not working&quot;),<br>                awaitItem()<br>            )<br>            coVerify(exactly = 1) {<br>                getCurrencyRateUseCase(currencyCode)<br>            }<br>            cancelAndIgnoreRemainingEvents()<br>        }<br>    }<br>}</pre><h3>Important Difference Between Both Approaches</h3><p>Without Turbine, we usually test the final value:</p><pre>assertEquals(<br>    AppState.Success(apiResponse),<br>    viewModel.appState.value<br>)</pre><p>This is simple and valid.</p><p>But it does not clearly verify all intermediate emissions.</p><p>For example, it does not clearly show this flow:</p><pre>Init -&gt; Loading -&gt; Success</pre><p>With Turbine, we can verify every emitted state step by step:</p><pre>viewModel.appState.test {<br>    assertEquals(AppState.Init, awaitItem())<br>    assertEquals(AppState.Loading, awaitItem())<br>    assertEquals(AppState.Success(apiResponse), awaitItem())<br>}</pre><p>So, Turbine is not compulsory, but it is very helpful when we want to test complete Flow emission order.</p><h3>Conclusion</h3><p>In this article, we learned how to unit test a ViewModel that exposes UI state using Kotlin StateFlow.</p><p>We tested the same ViewModel in two ways.</p><p>First, we tested without Turbine by checking the final value of StateFlow using viewModel.appState.value.</p><p>Then, we tested with Turbine by collecting and verifying each emission one by one.</p><p>Both approaches are valid.</p><p>If we only care about the final state, normal StateFlow value testing is enough.</p><p>If we want to verify complete UI state changes like:</p><pre>Init -&gt; Loading -&gt; Success</pre><p>then Turbine makes the test much cleaner and easier to read.</p><p>Thank you for reading. If this article helped you, please clap and share your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6143ea982ab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Code Is Ever “Best” Code]]></title>
            <link>https://medium.com/@myofficework000/no-code-is-ever-best-code-99cf2464c3da?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/99cf2464c3da</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[code-review-process]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 14:38:10 GMT</pubDate>
            <atom:updated>2026-02-05T18:28:27.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Czq8zOp-9tfIlnI1" /><figcaption>Photo by <a href="https://unsplash.com/@writecodenow?utm_source=medium&amp;utm_medium=referral">Boitumelo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are here, then chances are that you were trying to learn best practices of code review. The first time someone tore apart my code in a review, I remember staring at the screen with my jaw tight and my ego bruised. I had stayed late to finish that feature. I thought it was clean, clever, even elegant. The review came back covered in comments. Naming issues. Edge cases I hadn’t considered. A performance concern that hadn’t even crossed my mind.</p><p>At the time, it felt like criticism. Years later, I see it for what it really was. That review didn’t just improve my code. It improved me.</p><p>After more than a decade in the industry, code review is still one of the most important parts of my job. Not because it catches mistakes, although it does plenty of that, but because it shapes how we build software and how we grow as engineers together.</p><p>So, let’s get into it.</p><h3>Code Review Is Where Software Engineering Actually Happens</h3><p>Writing code is only part of the job. Code review is where that code is tested against reality. Before anything gets merged into the main branch, another human being takes a careful look. That simple act changes everything.</p><p>I’ve seen reviews catch security issues that would have exposed customer data. I’ve seen someone spot a tiny logic flaw that would have caused silent data corruption months later. I’ve seen a teammate suggest a simpler design that cut future maintenance work in half. None of that happens when we code in isolation.</p><p>Code review helps eliminate bugs early, when they are still cheap and easy to fix. It improves overall quality because more than one brain has shaped the solution. It often enhances functionality because reviewers ask questions like “What happens if this input is empty?” or “Should this support future use cases?” Over time, this habit reduces long-term maintenance costs. Cleaner code, clearer intent, fewer surprises.</p><p>But beyond the technical benefits, code review aligns the team. It spreads knowledge. It builds shared ownership of the system instead of leaving parts of it locked inside one person’s head.</p><h3>How My Perspective Changed Over the Years</h3><p>Early in my career, I treated code reviews like inspections. I was looking for mistakes. I wanted to prove I could spot issues others missed. If I’m honest, there was a bit of ego involved. Catching a bug felt like winning.</p><p>Over time, that mindset shifted. Now I go into a review assuming the author is smart and did their best with the information they had. My job isn’t to judge their competence. My job is to help us build better software together.</p><p>I’ve also learned that I am wrong more often than I’d like to admit. Many times I’ve left a confident comment suggesting a “better” approach, only to have the author explain a constraint I didn’t know about. Those moments keep me humble. Reviews are conversations, not verdicts.</p><p>Today, I focus less on stylistic preferences and more on real-world impact. Is this secure? Will this perform well under load? Is this readable enough that someone new to the team can understand it next year? Will this design still make sense when the product grows?</p><h3>What I Really Look For in a Code Review</h3><p>When I open a pull request, I try to understand the intent first. What problem is this solving? What trade-offs were made? Without that context, it’s easy to give feedback that sounds smart but isn’t helpful.</p><p>Security is always near the top of my mind. I look for places where user input flows into the system. Is anything being trusted too easily? Are we accidentally exposing internal data? I once reviewed a change that logged full request payloads for debugging. It seemed harmless until we realized those payloads sometimes contained personal information. That review saved us from a serious compliance problem.</p><p>Performance is another frequent theme. I’m not hunting for micro-optimizations. I’m looking for patterns that don’t scale. A database query inside a loop. Repeated network calls that could be batched. Large objects being rebuilt over and over. These are the kinds of things that work fine in testing and fall apart in production.</p><p>Clarity of logic might be the most underrated part of review. If I have to read a function three times to understand what it does, something needs to change. Complex conditionals, deeply nested branches, and vague variable names are all signs that future engineers will struggle. I often ask the author to rename things or split logic into smaller pieces, not because the code is wrong, but because it’s hard to follow.</p><p>Test coverage tells me how confident we can be in this change. I’m not looking for perfect numbers. I’m looking for thoughtful tests that cover the important paths and edge cases. If a piece of logic is tricky, I want to see a test that proves it behaves the way we think it does. Tests are like a second explanation of the code, written in a different language.</p><p>Long-term maintainability ties all of this together. I ask myself what happens when someone has to modify this in six months. Is the structure flexible enough? Are assumptions clearly visible? Or are we building something fragile that only the original author understands?</p><h3>How to Give Feedback Without Being “That Reviewer”</h3><p>Learning how to write good review comments took me years. Technical skill is only half the equation. Communication is the other half.</p><p>I try to frame feedback as suggestions, not orders. Saying “Consider renaming this variable to make its purpose clearer” feels very different from “This name is wrong.” One invites collaboration. The other shuts it down.</p><p>Being specific is crucial. Vague comments like “This is confusing” are frustrating. Instead, I try to explain exactly where I got lost and why. Maybe a function does two different things and could be split. Maybe a name suggests one behavior while the code does another. Explaining the “why” behind a suggestion helps the author learn, and sometimes helps me realize my concern isn’t valid after all.</p><p>Tone matters more than we think. There’s a real person on the other side of that pull request. I assume positive intent and write as if we’re sitting side by side, not arguing across a screen.</p><p>Timing also plays a huge role. Fast reviews build momentum and trust. When feedback comes days later, the author has already mentally moved on. I’ve been on both sides of that delay, and it’s frustrating every time. Even a quick pass that says “I’ll do a deeper review later, but this part looks good” keeps things moving.</p><h3>Advice for the People Writing the Code</h3><p>After reviewing thousands of changes, I’ve noticed patterns in pull requests that go smoothly.</p><p>The best authors review their own code before anyone else sees it. They read it like a stranger would. They catch obvious typos, dead code, and confusing names themselves. That small effort makes a big difference.</p><p>Smaller pull requests are easier to review well. When a change touches twenty files and introduces three new concepts, it’s hard to give thoughtful feedback. When it’s focused and scoped, reviewers can dig deeper and provide better input.</p><p>A good description at the top of the pull request is gold. What problem are we solving? Are there any trade-offs or limitations? Is there anything specific you want feedback on? That context turns a blind review into a meaningful conversation.</p><p>Responding to feedback with maturity is just as important. Not every comment needs to be accepted, but every comment deserves consideration. I respect authors who ask questions, explain their reasoning, and are open to changing their approach. Defensiveness slows everyone down. Curiosity speeds everyone up.</p><h3>Code Review as a Team Sport</h3><p>The best teams I’ve worked on treat code review as a shared responsibility, not a gatekeeping process. Everyone reviews. Everyone gets reviewed. Knowledge flows in all directions, not just from senior to junior.</p><p>Over time, this builds a strong sense of collective ownership. No part of the codebase belongs to just one person. If someone leaves the team, their knowledge doesn’t disappear with them because it has been spread through countless reviews.</p><p>Automation helps, of course. Linters, formatters, and static analysis tools catch a lot of small issues before humans even get involved. That’s great. It frees us to focus on the things tools can’t easily judge, like design decisions, readability, and whether the solution actually fits the problem.</p><p>But tools don’t build trust. People do. The conversations in code reviews, the back-and-forth, the shared problem solving, that’s where real engineering culture is formed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ao84Iun5kkJs8DTYIeNfwg.png" /></figure><h3>Still Learning, Every Week…</h3><p>After all these years, I still learn something new from reviews almost every week. A different way to structure logic. A library I didn’t know existed. A subtle security concern. A cleaner naming pattern. Sometimes the person teaching me is five years into their career. Sometimes it’s their first year.</p><blockquote>That’s the quiet magic of code review. It keeps us honest. It keeps us connected. It reminds us that no matter how experienced we are, we don’t have all the answers.</blockquote><p>No code is ever “best” code. It can always be clearer, safer, faster, more thoughtful. Code review isn’t about reaching perfection. It’s about moving a little closer together, one change at a time, with respect for the craft and for the people practicing it.</p><blockquote>If you found this article helpful or have any questions, feel free to reach out to me on <a href="https://www.linkedin.com/in/myofficework/"><strong><em>Linkedin</em></strong></a><em> , </em><a href="https://github.com/myofficework000/"><strong><em>GitHub</em></strong></a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99cf2464c3da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Day 3/150: Contains Duplicate (LeetCode 217)]]></title>
            <link>https://blog.stackademic.com/dsa-day-3-150-contains-duplicate-leetcode-217-64e5769d93ef?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e5769d93ef</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[faang]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 16:27:08 GMT</pubDate>
            <atom:updated>2026-01-27T07:50:38.539Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://leetcode.com/problems/contains-duplicate/description/">217. Contains Duplicate</a> | <strong>Difficulty:</strong> Easy | <strong>Topics:</strong> Arrays, HashSet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQHQAjMBts7lyslIDpJjRw.png" /></figure><h3>Problem Statement (LeetCode)</h3><p>Given an integer array nums, return <strong>true</strong> if any value appears <strong>at least twice</strong> in the array, and return <strong>false</strong> if every element is <strong>distinct</strong>.</p><p><strong>Example 1:</strong></p><p><strong>Input:</strong> nums = [1,2,3,1]</p><p><strong>Output:</strong> true</p><p><strong>Explanation: </strong>The element 1 occurs at the indices 0 and 3.</p><p><strong>Example 2:</strong></p><p><strong>Input:</strong> nums = [1,2,3,4]</p><p><strong>Output:</strong> false</p><p><strong>Explanation: </strong>All elements are distinct.</p><p><strong>Constraints:</strong></p><ul><li>1 &lt;= nums.length &lt;= 105</li><li>-109 &lt;= nums[i] &lt;= 109</li></ul><h3>About This Challenge</h3><p>As part of my <strong>150 Days DSA Challenge</strong>, I’m solving one problem every day with a focus on:</p><ul><li>Step-by-step thinking</li><li>Understanding multiple approaches</li><li>Interview-friendly optimizations</li></ul><p>This problem looks easy — but it’s a <strong>great example of how to evolve a solution</strong>.</p><h3>🧠 Learning Path for This Problem</h3><p>We’ll solve this problem in <strong>5 ways</strong>, starting from the most basic idea and moving toward the <strong>best interview solution</strong>.</p><h3>🔹 Way 1: Sorting the Array</h3><h3>Intuition</h3><p>If the array is sorted, <strong>duplicate elements will be adjacent</strong>.</p><h3>Approach</h3><ol><li>Sort the array</li><li>Traverse once</li><li>Compare current element with the previous one</li></ol><pre>class Solution {<br>    fun containsDuplicate(nums: IntArray): Boolean {<br>        nums.sort()<br><br>        for (i in 1 until nums.size) {<br>            if (nums[i] == nums[i - 1]) {<br>                return true<br>            }<br>        }<br>        return false<br>    }<br>}</pre><h3>Complexity</h3><ul><li><strong>Time:</strong> O(n log n) → sorting</li><li><strong>Space:</strong> O(1) (ignoring sort internals)</li></ul><h3>❌ Drawback</h3><ul><li>Sorting is unnecessary</li><li>Changes original order</li><li>Not optimal for interviews</li></ul><h3>🔹 Way 2: Kotlin distinct() Method</h3><h3>Intuition</h3><p>If duplicates exist, the <strong>distinct array size</strong> will be smaller than the original.</p><h3>Approach</h3><ul><li>Remove duplicates using distinct()</li><li>Compare sizes</li></ul><pre>class Solution {<br>    fun productExceptSelf(nums: IntArray): IntArray {<br>        <br>    }<br>}</pre><h3>Complexity</h3><ul><li><strong>Time:</strong> O(n)</li><li><strong>Space:</strong> O(n)</li></ul><h3>❌ Drawback</h3><ul><li>Uses extra memory</li><li>Hides logic (bad for interviews)</li><li>Less control</li></ul><h3>🔹 Way 3: Brute Force (Two Loops ❌)</h3><h3>Intuition</h3><p>Compare every element with every other element.</p><pre>class Solution {<br>    fun containsDuplicate(nums: IntArray): Boolean {<br>        for (i in nums.indices) {<br>            for (j in i + 1 until nums.size) {<br>                if (nums[i] == nums[j]) {<br>                    return true<br>                }<br>            }<br>        }<br>        return false<br>    }<br>}</pre><h3>Complexity</h3><ul><li><strong>Time:</strong> O(n²)</li><li><strong>Space:</strong> O(1)</li></ul><h3>❌ Why This Is Bad</h3><ul><li>Will <strong>TLE</strong> for large inputs</li><li>Interviewers will reject this</li></ul><h3>🔹 Way 4: HashMap (Overkill ⚠️)</h3><h3>Intuition</h3><p>Count frequency of each element.</p><pre>class Solution {<br>    fun containsDuplicate(nums: IntArray): Boolean {<br>        val map = HashMap&lt;Int, Int&gt;()<br><br>        for (num in nums) {<br>            map[num] = map.getOrDefault(num, 0) + 1<br>            if (map[num]!! &gt; 1) {<br>                return true<br>            }<br>        }<br>        return false<br>    }<br>}</pre><h3>Complexity</h3><ul><li><strong>Time:</strong> O(n)</li><li><strong>Space:</strong> O(n)</li></ul><h3>❌ Why Not Preferred</h3><ul><li>Extra storage</li><li>Frequency not required</li><li>HashSet is simpler</li></ul><h3>🔹 Way 5: HashSet (✅ Best Solution)</h3><h3>Key Insight</h3><p>A <strong>Set only stores unique elements</strong>.</p><ul><li>If insertion fails → duplicate found</li></ul><pre>class Solution {<br>    fun containsDuplicate(nums: IntArray): Boolean {<br>        val set = HashSet&lt;Int&gt;()<br><br>        for (num in nums) {<br>            if (!set.add(num)) {<br>                return true<br>            }<br>        }<br>        return false<br>    }<br>}</pre><h3>Complexity</h3><ul><li><strong>Time:</strong> O(n)</li><li><strong>Space:</strong> O(n)</li></ul><h3>✅ Why This Is Best</h3><ul><li>Fast</li><li>Clean</li><li>Early exit</li><li>Interview-friendly</li></ul><h3>🏆 Final Verdict: Best Approach</h3><h3>✅ Way 5: HashSet</h3><p><strong>Why?</strong></p><ul><li>Minimal logic</li><li>Optimal time</li><li>Early termination</li><li>Exactly what interviewers expect</li></ul><h3>📊 Learning Sequence (Best Order to Understand)</h3><p>1️⃣ Two loops (understand the problem)<br>2️⃣ Sorting (pattern recognition)<br>3️⃣ distinct() (language feature awareness)<br>4️⃣ HashMap (when frequency is needed )<br>5️⃣ <strong>HashSet (final &amp; best)</strong></p><h3>🎯 Key Takeaways</h3><ul><li>Always start simple, then optimize</li><li>Hashing is powerful for uniqueness problems</li><li>Clean code beats clever tricks</li></ul><p>✅ <strong>Day 3/150 completed</strong><br>Day 4 coming tomorrow 🚀🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e5769d93ef" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/dsa-day-3-150-contains-duplicate-leetcode-217-64e5769d93ef">DSA Day 3/150: Contains Duplicate (LeetCode 217)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Day 2/150: Best Time to Buy and Sell Stock (LeetCode 121)]]></title>
            <link>https://blog.devgenius.io/dsa-day-2-150-best-time-to-buy-and-sell-stock-leetcode-121-8200eb449290?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8200eb449290</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[faang]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 20:40:08 GMT</pubDate>
            <atom:updated>2026-01-22T08:07:56.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hL8y9flHpwADC8OB5-t4MA.png" /></figure><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/"><strong>121. Best Time to Buy and Sell Stock</strong></a><br> <strong>Difficulty:</strong> Easy<br> <strong>Topics:</strong> Arrays, Greedy</p><h3>Problem Statement (LeetCode)</h3><p>You are given an array prices where prices[i] represents the price of a stock on the <strong>i-th day</strong>.</p><p>You want to maximize your profit by:</p><ul><li>Choosing <strong>one day to buy</strong></li><li>Choosing a <strong>different future day to sell</strong></li></ul><p>Return the <strong>maximum profit</strong> you can achieve.<br> If no profit is possible, return 0.</p><h4>Example 1</h4><p><strong>Input:</strong><br> prices = [7,1,5,3,6,4]</p><p><strong>Output:</strong><br> 5</p><p><strong>Explanation:</strong><br> Buy at price 1 (day 2) and sell at price 6 (day 5)<br> Profit = 6 - 1 = 5</p><h4>Example 2</h4><p><strong>Input:</strong><br> prices = [7,6,4,3,1]</p><p><strong>Output:</strong><br> 0</p><p><strong>Explanation:</strong><br> Prices are decreasing, so no profitable transaction is possible.</p><h4>Constraints</h4><ul><li>1 &lt;= prices.length &lt;= 10^5</li><li>0 &lt;= prices[i] &lt;= 10^4</li></ul><h3>About This Challenge</h3><p>As part of my<strong> 150</strong> <strong>Days DSA Challenge</strong>, I’m solving <strong>one problem every day</strong> with a focus on:</p><ul><li>Understanding patterns</li><li>Interview intuition</li><li>Writing clean, readable code</li></ul><p>This problem is a classic <strong>greedy + single pass</strong> question that frequently appears in interviews.</p><h3>Brute Force Approach (What NOT to Do)</h3><h3>Intuition</h3><p>Try all possible pairs:</p><ul><li>Buy on day i</li><li>Sell on day j &gt; i</li><li>Track the maximum profit</li></ul><h3>Why This Fails</h3><ul><li>Two nested loops</li><li>Too slow for large inputs</li></ul><p><strong>Time Complexity:</strong> O(n²)<br> This will <strong>TLE</strong> for large arrays.</p><p>Interviewers expect better.</p><h3>Optimized Approach (Greedy + Single Pass)</h3><h3>Key Insight</h3><p>To maximize profit:</p><ul><li>Always buy at the <strong>lowest price so far</strong></li><li>Try selling at the <strong>current price</strong></li><li>Track the best profit seen</li></ul><p>We don’t need to check all pairs.</p><h3>Intuition (Interview-Friendly)</h3><p>As we move day by day:</p><ul><li>Keep track of the <strong>minimum buying price</strong></li><li>At each day, calculate:</li><li>profit = currentPrice - minBuyPrice</li><li>Update the maximum profit if it’s better</li></ul><p>This ensures:</p><ul><li>Buy happens before sell</li><li>Only one transaction</li><li>Single traversal</li></ul><h3>Approach</h3><p>STEP 1: Initialize:</p><ul><li>buy → first day price</li><li>profit → 0</li></ul><p>STEP 2: Traverse prices:</p><ul><li>If current price &lt; buy → update buy</li><li>Else → calculate profit and update max profit</li></ul><p>STEP 3: Return profit</p><h3>Final solution</h3><pre>class Solution {<br>    fun maxProfit(prices: IntArray): Int {<br>    var buyPrice = prices[0]<br>    var profit = 0<br><br>    for(currentPrice in prices){<br>        if(currentPrice &lt; buyPrice){<br>            buyPrice = currentPrice<br>        } else if(profit &lt; (currentPrice - buyPrice)){<br>            profit = currentPrice - buyPrice<br>        }<br>    }<br>    return profit<br>    }<br>}</pre><h3>Step-by-Step Walkthrough</h3><p><strong>Input</strong></p><pre>prices = [7, 1, 5, 3, 6, 4]</pre><ul><li><strong>Day 1:</strong> buyPrice = 7, profit = 0</li><li><strong>Day 2:</strong> price = 1 → update buyPrice = 1</li><li><strong>Day 3:</strong> price = 5 → profit = 4</li><li><strong>Day 4:</strong> price = 3 → no change</li><li><strong>Day 5:</strong> price = 6 → profit = 5</li><li><strong>Day 6:</strong> price = 4 → no change</li></ul><p><strong>Final Answer:</strong> 5</p><h3>Why This Works</h3><ul><li>Always track the <strong>lowest buy price</strong></li><li>Sell only <strong>after buying</strong></li><li>Single pass with greedy choice ensures maximum profit</li></ul><h3>Complexity</h3><ul><li><strong>Time:</strong> O(n)</li><li><strong>Space:</strong> O(1)</li></ul><h3>Interview Follow-Ups</h3><ul><li>Multiple transactions → LeetCode 122</li><li>Transaction fee → Greedy + DP</li><li>Cooldown → DP</li></ul><h3>Key Takeaways</h3><ul><li>Track <strong>min so far / max profit</strong></li><li>Greedy problems often need one pass</li><li>Prefer clean logic over brute force</li></ul><p><strong>Day 2/150 completed.</strong><br><strong>Day 3 coming tomorrow 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8200eb449290" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/dsa-day-2-150-best-time-to-buy-and-sell-stock-leetcode-121-8200eb449290">DSA Day 2/150: Best Time to Buy and Sell Stock (LeetCode 121)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Day 1/150:Two Sum(LeetCode 1)]]></title>
            <link>https://medium.com/@myofficework000/dsa-day-1-150-two-sum-leetcode-1-e89f9a5bd2d4?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e89f9a5bd2d4</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[faang]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 20:45:59 GMT</pubDate>
            <atom:updated>2026-01-19T20:45:59.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_8eYI8KQhFoVoN0HBhVQg.png" /></figure><p><strong>1. </strong><a href="https://leetcode.com/problems/two-sum/description/"><strong>Two Sum</strong></a><br> <strong>Difficulty:</strong> Easy<br> <strong>Topics:</strong> Arrays, HashMap, Two Pointers</p><h3>Problem Statement (LeetCode)</h3><p>Given an array of integers nums and an integer target, return <strong>indices of the two numbers</strong> such that they add up to target.</p><p>You may assume that:</p><ul><li>Each input has <strong>exactly one solution</strong></li><li>You <strong>may not use the same element twice</strong></li><li>You can return the answer in any order</li></ul><h4>Example 1</h4><p><strong>Input:</strong><br> nums = [2,7,11,15], target = 9</p><p><strong>Output:</strong><br> [0,1]</p><h4>Example 2</h4><p><strong>Input:</strong><br> nums = [3,2,4], target = 6</p><p><strong>Output:</strong><br> [1,2]</p><h4>Constraints</h4><ul><li>2 &lt;= nums.length &lt;= 10^4</li><li>-10^9 &lt;= nums[i] &lt;= 10^9</li><li>-10^9 &lt;= target &lt;= 10^9</li><li>Only one valid answer exists</li></ul><h4>About This Challenge</h4><p>I’m continuing my 1<strong>50 Days DSA Challenge</strong>, where I solve <strong>one problem every day</strong> with a strong focus on:</p><ul><li>Interview intuition</li><li>Trade-offs between approaches</li><li>How solutions evolve during real interviews</li></ul><p><strong>Two Sum</strong> is a perfect problem for this because it naturally demonstrates:</p><ul><li>Brute force thinking</li><li>Optimization using HashMap</li><li>Alternative constraints-based solutions</li></ul><p>Exactly how interviews usually flow.</p><h3>Brute Force Approach (Baseline Thinking)</h3><h3>Intuition</h3><p>The most straightforward idea is:</p><ul><li>Pick one number</li><li>Try pairing it with every other number</li><li>Check if their sum equals target</li></ul><p>This mirrors how most people think initially — and that’s <strong>completely fine</strong>.</p><h3>Approach</h3><ul><li>Use <strong>two nested loops</strong></li><li>Check all possible pairs</li><li>Return indices when nums[i] + nums[j] == target</li></ul><h3>Code (Brute Force)</h3><pre>fun twoSum(nums: IntArray, target: Int): IntArray {<br>    for (i in nums.indices) {<br>        for (j in i + 1 until nums.size) {<br>            if (nums[i] + nums[j] == target) {<br>                return intArrayOf(i, j)<br>            }<br>        }<br>    }<br>    return intArrayOf()<br>}</pre><h3>Complexity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*oz87lrR4jHmOMGA-Ba9YXA.png" /></figure><ul><li><strong>Time Complexity:</strong> O(n²)</li><li><strong>Space Complexity:</strong> O(1)</li></ul><h3>Interview Note</h3><p>This solution works but does not scale.<br> The interviewer will usually ask:</p><blockquote><em>“Can you optimize this?”</em></blockquote><h3>Optimized Approach Using HashMap (Most Expected)</h3><h3>Key Insight</h3><p>For every number x, check whether target - x already exists.</p><p>This removes the nested loop.</p><pre>fun twoSum(nums: IntArray, target: Int): IntArray {<br>    val map = HashMap&lt;Int, Int&gt;()<br><br>    for (i in nums.indices) {<br>        val complement = target - nums[i]<br>        map[complement]?.let {<br>            return intArrayOf(it, i)<br>        }<br>        map[nums[i]] = i<br>    }<br>    return intArrayOf()<br>}</pre><h3>Complexity</h3><ul><li><strong>Time Complexity:</strong> O(n)</li><li><strong>Space Complexity:</strong> O(n)</li></ul><h3>Why This Works</h3><ul><li>Single pass through the array</li><li>Constant-time lookup using HashMap</li><li>No duplicate checks</li></ul><p>This is the <strong>standard interview solution</strong>.</p><h3>If Interviewer Says: “Don’t Use HashMap”</h3><p>Now constraints change:</p><ul><li>Extra space restricted</li><li>Better than O(n²) expected</li></ul><p>This leads to <strong>sorting + two pointers</strong>.</p><h3>Two Pointers Approach (Without HashMap)</h3><h3>Important Detail</h3><p>Sorting changes indices, so we store <strong>value + original index</strong> together.</p><h3>Kotlin Code (Sorting + Two Pointers)</h3><pre>fun twoSum(nums: IntArray, target: Int): IntArray {<br>    val arr = nums.mapIndexed { index, value -&gt; Pair(value, index) }<br>        .sortedBy { it.first }<br><br>    var left = 0<br>    var right = arr.size - 1<br><br>    while (left &lt; right) {<br>        val sum = arr[left].first + arr[right].first<br>        when {<br>            sum == target -&gt; return intArrayOf(arr[left].second, arr[right].second)<br>            sum &lt; target -&gt; left++<br>            else -&gt; right--<br>        }<br>    }<br>    return intArrayOf()<br>}</pre><h3>Complexity</h3><ul><li><strong>Time Complexity:</strong> O(n log n)</li><li><strong>Space Complexity:</strong> O(n)</li></ul><h3>When This Is Useful</h3><ul><li>HashMap not allowed</li><li>Interviewer wants alternative thinking</li><li>Constraint-driven optimization discussion</li></ul><pre>| Approach     | Time       | Space | Use Case           |<br>| ------------ | ---------- | ----- | ------------------ |<br>| Brute Force  | O(n²)      | O(1)  | Baseline           |<br>| HashMap      | O(n)       | O(n)  | Best &amp; most common |<br>| Two Pointers | O(n log n) | O(n)  | HashMap restricted |</pre><h3>Key Takeaways</h3><ul><li>Always start with brute force</li><li>Optimize step-by-step</li><li>HashMap converts pair search into lookup</li><li>Constraints often drive the final solution</li><li>Interviews care about <strong>thought process</strong></li></ul><p><strong>Day 1/150 completed.</strong><br> Next problem coming tomorrow 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e89f9a5bd2d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Smart Image Downloader: Batch Files with Real-Time Progress]]></title>
            <link>https://medium.com/@myofficework000/building-a-smart-image-downloader-batch-files-with-real-time-progress-dd3d066f25c7?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd3d066f25c7</guid>
            <category><![CDATA[workmanager]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 14:50:04 GMT</pubDate>
            <atom:updated>2025-12-12T14:50:04.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETz-YF18FkgZbszKdaQwNw.png" /></figure><blockquote><em>Download Wars: How to Download 100 Images — Three at a Time — and Show Real-Time Progress Without Losing Your Mind</em></blockquote><p>This article walks you through the exact problem, the design choices, the implementation, and practical improvements in plain human words. If you’re preparing for an interview, building a feature for a product, or just love clean engineering, this will take you from “what even is the problem?” to “this works, is testable, and survives app restarts.”</p><h3>Problem statement (short &amp; sharp)</h3><p>You have <strong>100 image URLs</strong>. The app must:</p><ul><li>Show a list of all images (filename, status, progress %).</li><li>Provide a <strong>“Download All”</strong> button.</li><li>When pressed, download images with <strong>maximum concurrency = 3</strong> (only three downloads at any time).</li><li>Show <strong>live percentage progress</strong> for each image in the UI.</li><li>Persist/continue downloads across configuration changes, backgrounding, or if the OS kills the app (use WorkManager).</li><li>Save files to a specific folder (/pictures/download_test/) and mark failures clearly.</li></ul><p>That’s the spec. Nothing fuzzy. Now let’s break it down.</p><h3>Why this is trickier than it looks</h3><ul><li>UI updates must be <strong>live</strong> and <strong>per-item</strong> (100 separate progress streams).</li><li>Concurrency control: naive launching of 100 coroutines can overwhelm network, CPU and battery.</li><li>Surviving process death: in-memory state is gone — need WorkManager or a persistent store.</li><li>Calculating progress per file requires streaming and reporting bytes read vs total bytes.</li><li>Handling partial downloads, retries, backoff, and filesystem permissions (Android scoped storage) add complexity.</li><li>UX: show meaningful statuses (NOT_STARTED, QUEUED, DOWNLOADING, PAUSED, COMPLETED, FAILED).</li></ul><p>So design the solution to be robust, observable, and testable.</p><h3>High-level design — components &amp; responsibility</h3><ol><li><strong>UI (Jetpack Compose)</strong><br> Presents a list, “Download All” button, per-item progress bars and status text. Observes a StateFlow/LiveData from ViewModel.</li><li><strong>ViewModel</strong><br> Exposes the Flow of items and kickstarts the WorkManager job. Translates persisted progress -&gt; UI state.</li><li><strong>WorkManager Worker (CoroutineWorker)</strong><br> Runs in background, survives app kills. Coordinates the downloads (one WorkRequest handles the 100 URLs). Uses concurrency control internally (Semaphore with 3 permits) to perform up to 3 parallel downloads.</li><li><strong>Download progress store (shared state)</strong><br> A persistent-ish place that both Worker and UI can read/write. Could be: A lightweight Room table (best for persistence + queries), or A simpler approach: WorkManager setProgress() for each worker + StateFlow in a singleton (if you accept weaker persistence).<br> I recommend Room for production; for interview/demo, a MutableStateFlow singleton plus WorkManager progress is fine.</li><li>Downloader(OkHttp)<br> Streams bytes and reports progress per chunk.</li><li><strong>File storage manager</strong><br> Writes files to /pictures/download_test/ using Android APIs and respects scoped storage rules.</li></ol><h3>Step-by-step breakdown implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0XcYlhTTRuKrVSQk" /><figcaption>Photo by <a href="https://unsplash.com/@beyzaayurtkuran?utm_source=medium&amp;utm_medium=referral">beyza yurtkuran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Step 1 — Define the data model</h4><p>Small, immutable model to represent UI state per image.</p><pre>data class ImageDownloadItem(<br>    val url: String,<br>    val fileName: String = url.substringAfterLast(&quot;/&quot;),<br>    val progress: Int = 0,<br>    val status: DownloadStatus = DownloadStatus.NOT_STARTED,<br>    val error: String? = null<br>)</pre><pre>enum class DownloadStatus { NOT_STARTED, QUEUED, DOWNLOADING, COMPLETED, FAILED }</pre><h4>Step 2 — Create a progress store</h4><p>For demo: a MutableStateFlow&lt;Map&lt;String, ImageDownloadItem&gt;&gt;.<br> For production: create a Room table image_downloads (url primary key, status, progress, path, error).</p><p>Example (singleton StateFlow approach):</p><pre>object DownloadProgressStore {<br>    private val _map = MutableStateFlow&lt;Map&lt;String, ImageDownloadItem&gt;&gt;(emptyMap())<br>    val map = _map.asStateFlow()</pre><pre>    fun init(urls: List&lt;String&gt;) {<br>        val m = urls.associateWith { ImageDownloadItem(url = it) }<br>        _map.value = m<br>    }</pre><pre>    fun update(url: String, progress: Int? = null, status: DownloadStatus? = null, error: String? = null) {<br>        val copy = _map.value.toMutableMap()<br>        val cur = copy[url] ?: ImageDownloadItem(url)<br>        copy[url] = cur.copy(<br>            progress = progress ?: cur.progress,<br>            status = status ?: cur.status,<br>            error = error ?: cur.error<br>        )<br>        _map.value = copy<br>    }<br>}</pre><h3>Step 3 — The Worker: concurrency + progress</h3><p>Use CoroutineWorker for coroutine support. Inside doWork():</p><ol><li>Read URLs passed via workDataOf(&quot;urls&quot; to urlsArray).</li><li>Use a Semaphore(3) to restrict concurrency.</li><li>Launch coroutines to download each URL; each coroutine acquires permit, streams via OkHttp, writes file, updates progress store.</li><li>Use setProgress() on the Worker to allow WorkManager to persist some progress at the worker level (optional).</li><li>Handle exceptions with retries or set FAILED.</li></ol><p>Key points inside download loop:</p><ul><li>Use response.body.byteStream() and contentLength()</li><li>After each buffer write, compute (downloaded * 100 / total).toInt() and update store.</li><li>If contentLength() is unknown (-1), you can show indeterminate progress or estimate.</li></ul><p>Example core snippet (pseudocode):</p><pre>val semaphore = Semaphore(3)<br>coroutineScope {<br>  urls.map { url -&gt;<br>    async {<br>      semaphore.withPermit {<br>         DownloadProgressStore.update(url, status = QUEUED)<br>         try {<br>           DownloadProgressStore.update(url, status = DOWNLOADING, progress = 0)<br>           downloadAndSave(url) { bytesRead, total -&gt; <br>             val percent = computePercent(bytesRead, total)<br>             DownloadProgressStore.update(url, progress = percent)<br>           }<br>           DownloadProgressStore.update(url, status = COMPLETED, progress = 100)<br>         } catch(e) {<br>           DownloadProgressStore.update(url, status = FAILED, error = e.message)<br>         }<br>      }<br>    }<br>  }.awaitAll()<br>}</pre><h3>Step 4 — ViewModel + UI binding</h3><p>ViewModel exposes itemsFlow: StateFlow&lt;List&lt;ImageDownloadItem&gt;&gt; derived from the store map. When user taps <strong>Download All</strong>:</p><ul><li>Call WorkManager to enqueue a unique OneTimeWorkRequest that passes the 100 URLs.</li><li>Optionally mark items as QUEUED before enqueuing.</li></ul><p>Compose UI collects the flow with collectAsState() and renders LazyColumn with each row:</p><ul><li>Title: file name</li><li>Status text</li><li>LinearProgressIndicator(progress = progress / 100f)</li><li>Percentage text</li><li>Retry button for failed items</li></ul><h3>Step 5 — File storage &amp; permissions</h3><ul><li>Use Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) or MediaStore (for shared pictures).</li><li>If targeting Android 11+ and you want public photos, use MediaStore APIs. For private app storage, external-files is simplest and needs no runtime permission.</li><li>Ensure correct file naming, avoid collisions (append UUID if duplicate).</li></ul><h4>Code snippets — compact, interview-friendly</h4><p><strong>ViewModel start download:</strong></p><pre>fun startDownloadAll(urls: List&lt;String&gt;, context: Context) {<br>    DownloadProgressStore.init(urls)<br>    val data = workDataOf(&quot;urls&quot; to urls.toTypedArray())<br>    val work = OneTimeWorkRequestBuilder&lt;ImageDownloadWorker&gt;()<br>                  .setInputData(data)<br>                  .build()<br>    WorkManager.getInstance(context)<br>        .enqueueUniqueWork(&quot;download-all&quot;, ExistingWorkPolicy.REPLACE, work)<br>}</pre><p>Worker download method (core idea — trimmed):</p><pre>suspend fun downloadAndSave(url: String, outputFile: File, progressCb: (read: Long, total: Long) -&gt; Unit) {<br>    val client = OkHttpClient()<br>    val req = Request.Builder()./service/https://medium.com/url(url).build()<br>    client.newCall(req).execute().use { resp -&gt;<br>        val body = resp.body ?: throw IOException(&quot;Empty body&quot;)<br>        val total = body.contentLength()<br>        var read = 0L<br>        body.byteStream().use { input -&gt;<br>            outputFile.outputStream().use { out -&gt;<br>                val buf = ByteArray(8_192)<br>                var r: Int<br>                while (input.read(buf).also { r = it } != -1) {<br>                    out.write(buf, 0, r)<br>                    read += r<br>                    progressCb(read, total)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>UX &amp; UX edge-cases — what to show the user</h3><ul><li><strong>Progress 0%</strong> — show NOT_STARTED or QUEUED.</li><li><strong>Indeterminate</strong> — when content-length unknown, show an indeterminate progress bar and a “Downloading…” label.</li><li><strong>Failures</strong> — show reason (network/timeouts) and a retry button (requeue single URL or re-run work with selected items).</li><li><strong>Pause/Resume</strong> — optional: pause all downloads (cancel worker) and resume later. For WorkManager, cancellation and re-queuing is straightforward.</li></ul><h3>Testing &amp; reliability</h3><p><strong>Unit tests</strong>: test DownloadProgressStore updates and ViewModel mapping.</p><p><strong>Instrumented tests</strong>: test Worker behavior with mocked network (use MockWebServer).</p><p><strong>Manual flows</strong>:</p><ul><li>App backgrounded: ensure Work continues (WorkManager).</li><li>App process killed: re-open app, UI should reload state from Room or WorkManager progress.</li></ul><p><strong>Edge cases</strong>:</p><ul><li>Slow networks — show per-item progress updates at throttled frequency to avoid UI overhead (update at most every 200–500 ms).</li><li>Large files — ensure streaming buffer sizes are adequate (8KB–64KB).</li></ul><h3>Optimizations &amp; best practices</h3><ol><li><strong>Throttle UI updates</strong>: Don’t update UI every few kilobytes — debounce to ~200ms to keep Compose performance smooth.</li><li><strong>Batch writes to DB</strong>: If using Room, avoid writing progress for every byte; batch or write at intervals.</li><li><strong>Retries</strong>: Apply exponential backoff for failures. WorkManager supports retry with Result.retry().</li><li><strong>Network prioritization</strong>: For mobile vs Wi-Fi, check ConnectivityManager and optionally pause large downloads on mobile data.</li><li><strong>Use WorkManager tags</strong>: Tag each work for easier cancellation or query.</li><li><strong>Security</strong>: Don’t embed credentials in URLs. If using signed URLs, ensure they expire gracefully and handle renewals.</li><li><strong>Memory</strong>: Stream directly to file; don’t keep whole files in memory.</li></ol><h3>Alternatives &amp; trade-offs</h3><ul><li><strong>Multiple WorkRequests (one per image)</strong>: You can enqueue 100 small WorkRequests and use WorkManager’s own scheduling/constraints. Pros: individual retries, better WorkManager tracking. Cons: managing concurrency across many WorkRequests is trickier; you’d need to coordinate concurrency externally (semaphore in each worker won’t coordinate across processes).</li><li><strong>Foreground Service</strong>: For long-running downloads giving a visible notification, use a Foreground Worker (WorkManager supports foreground services). This gives more user visibility and priority.</li><li><strong>Use DownloadManager</strong>: Android’s DownloadManager handles downloads, system notifications, and persistence. But it’s less flexible for per-byte progress integration in the UI and for custom retry logic.</li></ul><h3>Final thoughts — engineering philosophy for this task</h3><p>This feature looks like a simple “download all” button on the surface, but it’s a compact exercise in concurrency control, robust background execution, UX, and persistence. The key is to separate concerns:</p><ul><li>Keep download logic out of UI.</li><li>Make progress observable via a simple, testable store (Room or StateFlow).</li><li>Use WorkManager for OS-friendly background execution.</li><li>Optimize UI updates so the user sees smooth, accurate feedback.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*fvz2JgwNHtnPt_To.png" /></figure><p><em>Thank you for reading my article. I really appreciate your response.</em></p><p><em>Clap if this article helps you. If I got something wrong, please comment for improve.<br>let’s connect on </em><a href="https://www.linkedin.com/in/myofficework/"><strong><em>Linkedin</em></strong></a><strong><em> </em></strong><em>, </em><a href="https://github.com/myofficework000"><strong><em>GitHub</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd3d066f25c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Accessibility: Best Practices & Implementation]]></title>
            <link>https://medium.com/@myofficework000/android-accessibility-best-practices-implementation-93ec7f07302c?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ec7f07302c</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[accessibility-testing]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 19:22:41 GMT</pubDate>
            <atom:updated>2026-10-05T15:16:00.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*UbQiUp73Q8t-2luMn4uStg.png" /></figure><p><a href="https://developer.android.com/guide/topics/ui/accessibility"><strong>Accessibility</strong> </a>is a crucial aspect of <a href="https://developer.android.com/">Android app development</a>. It ensures that applications are usable by people with disabilities, including those with visual, auditory, motor, and cognitive impairments. This article explores accessibility principles, best practices, compliance standards like the <a href="https://commission.europa.eu/strategy-and-policy/policies/justice-and-fundamental-rights/disability/union-equality-strategy-rights-persons-disabilities-2021-2030/european-accessibility-act_en"><strong>European Accessibility Act (EAA)</strong></a>, Google’s recommendations, and practical implementation techniques.</p><h3>Why Accessibility Matters in Android</h3><h4>1. Inclusivity</h4><p>You build apps for <em>everyone</em>. <a href="https://www.a11yproject.com/"><strong>A11y </strong></a>ensures visually impaired users, elderly users, and users with motor or cognitive challenges can interact with your app smoothly.</p><h4>2. Legal Compliance</h4><p>Countries enforce strong accessibility laws:</p><ul><li><strong>EAA (EU)</strong> — Mandatory by <strong>June 28, 2025</strong></li><li><a href="https://www.ada.gov/"><strong>ADA (USA)</strong></a></li><li><a href="https://www.etsi.org/deliver/etsi_en/301500_301599/301549/03.02.01_60/en_301549v030201p.pdf"><strong>EN 301 549</strong></a></li></ul><p>Non-compliance can lead to fines and product bans.</p><h4>3. Better User Experience</h4><p>Accessibility is good UX: clear UI, readable text, correct focus behavior — benefits every user.</p><h4>4. Play Store Ranking Boost</h4><p>Google promotes apps with accessibility improvements.</p><h3>European Accessibility Act (EAA) &amp; Android Apps</h3><p>The <strong>European Accessibility Act (EAA)</strong> requires all digital services — websites and apps — to follow accessibility standards.</p><h4>Key EAA Requirements</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*l7CH-OLrS_zTkIgC9TSG3w.png" /></figure><h3>How to Align With EAA</h3><p>Follow <a href="https://www.w3.org/TR/WCAG21/"><strong>WCAG 2.1 AA guidelines</strong></a>, implemented through Android accessibility APIs.</p><h3>Who Must Comply?</h3><p>Any business offering software to EU users (even if headquartered outside EU).</p><p><strong>Key Requirements</strong>:</p><p>Support for assistive technologies like <a href="https://support.google.com/accessibility/android/answer/6007100?hl=en"><strong>TalkBack</strong></a>.</p><p>Proper <strong>color contrast</strong> and <strong>scalable text</strong>.</p><p>Accessible navigation and <strong>voice control</strong>.</p><p><strong>How to Ensure Compliance?</strong> Follow <strong>WCAG 2.1 AA</strong> guidelines and test your app with <strong>Google’s Accessibility Scanner</strong>.</p><h3>Google’s Accessibility Recommendations</h3><p>Google pushes developers to ensure:</p><h4>1. Provide Alternative Text</h4><p>Use contentDescription for icons/images.</p><h4>2. Maintain Color Contrast</h4><p>Use Material Theme dynamic colors or test with accessibility scanner.</p><h4>3. Correct Focus Order</h4><p>Avoid skipping or unexpected focus jumps.</p><h4>4. Semantic Roles</h4><p>Elements should expose correct accessibility types:</p><ul><li>Button</li><li>Switch</li><li>Heading</li><li>Link</li><li>Image</li></ul><h4>5. Test Using Tools</h4><ul><li>TalkBack</li><li>Accessibility Scanner</li><li>Lint’s accessibility warnings</li><li>Switch Access</li></ul><h3>Jetpack Compose Accessibility Examples (Complete Code)</h3><p>Below are practical examples you can directly use in production apps.</p><h3>1. Adding Descriptive Content for Images</h3><h4>❌ Wrong</h4><pre>Image(<br>    painter = painterResource(R.drawable.profile),<br>    contentDescription = null // bad: not decorative<br>)</pre><h4>✔ Correct</h4><pre>Image(<br>    painter = painterResource(R.drawable.profile),<br>    contentDescription = &quot;User profile picture&quot;<br>)</pre><h3>2. Mark Decorative Images as Not Important</h3><pre>Image(<br>    painter = painterResource(R.drawable.divider),<br>    contentDescription = null // GOOD for decorative images<br>)</pre><h3>3. Accessible Buttons With Semantic Labels</h3><pre>Button(<br>    onClick = { /*submit*/ },<br>    modifier = Modifier.semantics {<br>        contentDescription = &quot;Submit form&quot;<br>    }<br>) {<br>    Icon(Icons.Default.Check, contentDescription = null)<br>    Text(&quot;Submit&quot;)<br>}</pre><h3>4. Adding a Heading (TalkBack reads “Heading”)</h3><pre>Text(<br>    text = &quot;Account Settings&quot;,<br>    style = MaterialTheme.typography.headlineSmall,<br>    modifier = Modifier.semantics { heading() }<br>)</pre><h3>5. Accessible Switch Example</h3><pre>var isEnabled by remember { mutableStateOf(true) }<br><br>Row(<br>    verticalAlignment = Alignment.CenterVertically,<br>    modifier = Modifier<br>        .padding(16.dp)<br>        .semantics { role = Role.Switch }<br>) {<br>    Text(&quot;Enable Notifications&quot;)<br><br>    Switch(<br>        checked = isEnabled,<br>        onCheckedChange = { isEnabled = it },<br>        modifier = Modifier.semantics {<br>            stateDescription = if (isEnabled) &quot;Enabled&quot; else &quot;Disabled&quot;<br>        }<br>    )<br>}</pre><h3>6. Ensure Correct Focus Order</h3><pre>Column(<br>    modifier = Modifier.focusGroup()<br>) {<br>    Text(&quot;Login to continue&quot;)<br>    OutlinedTextField(...)<br>    Button(onClick = {}) { Text(&quot;Login&quot;) }<br>}</pre><h3>7. Dynamic Text Scaling (Font Scaling up to 200%)</h3><p>Compose supports this automatically, but avoid fixed sizes:</p><h4>❌ Wrong</h4><pre>Text(&quot;Hello&quot;, fontSize = 12.sp)</pre><h4>✔ Correct</h4><pre>Text(<br>    text = &quot;Hello&quot;,<br>    style = MaterialTheme.typography.bodyLarge<br>)</pre><h3>8. Custom Clickable Elements with Proper Semantics</h3><pre>Box(<br>    modifier = Modifier<br>        .clickable(onClick = { })<br>        .semantics { role = Role.Button }<br>) {<br>    Text(&quot;Continue&quot;)<br>}</pre><h3>9. Content Grouping &amp; Merging Semantics</h3><p>Useful when multiple elements should be announced together.</p><pre>Row(<br>    modifier = Modifier.semantics(mergeDescendants = true) {}<br>) {<br>    Icon(Icons.Default.Phone, contentDescription = null)<br>    Text(&quot;Call Support&quot;)<br>}</pre><h3>10. Error Message Accessibility With LiveRegion</h3><pre>val showError = remember { mutableStateOf(false) }<br><br>if (showError.value) {<br>    Text(<br>        &quot;Password is incorrect&quot;,<br>        color = Color.Red,<br>        modifier = Modifier.semantics { liveRegion = LiveRegionMode.Assertive }<br>    )<br>}</pre><p>TalkBack immediately announces the error.</p><h3>Accessibility Testing Checklist (2025)</h3><h3>✔ TalkBack Testing</h3><ul><li>Swipe navigation</li><li>Explore by touch</li><li>Verify buttons and labels</li><li>Check error announcements</li><li>Focus order must be predictable</li></ul><h3>✔ Keyboard Navigation</h3><ul><li>Tab navigation for all elements</li><li>Proper highlight focus</li></ul><h3>✔ Switch Access Testing</h3><ul><li>All clickable UI must be reachable</li></ul><h3>✔ Accessibility Scanner</h3><p>Google’s tool highlights:</p><ul><li>Low contrast</li><li>Small touch targets</li><li>Missing labels</li><li>Overlapping UI</li></ul><h3>✔ Font Scaling Test</h3><p>Settings → Display → Font size → Largest<br> UI must not break.</p><h3>✔ Color Blind Mode Testing</h3><p>Use Material dynamic colors + test monochrome mode on Pixel.</p><h3>Final Thoughts</h3><p>Accessibility is an investment — not an expense. With proper implementation, your app becomes:</p><ul><li>Legally compliant</li><li>Universally usable</li><li>Higher ranked in Play Store</li><li>More inclusive</li></ul><p>Jetpack Compose makes accessibility easier than ever with its <strong>semantics API</strong>, <strong>focus management</strong>, and <strong>live regions</strong>.</p><p><a href="https://github.com/myofficework000/AccessiblityDemo">GitHub - myofficework000/AccessiblityDemo: Android Accessibility Showcase App built using Jetpack Compose, This repository serves as a complete reference guide for Android developers, QA engineers, and designers on implementing native accessibility (TalkBack, Switch Access, High Contrast, Dynamic Text Scaling) across 15+ core Android UI components.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*z8mySz-cToT4Fd4S.png" /></figure><p><em>Thank you for reading my article. I really appreciate your response.</em></p><p><em>Clap if this article helps you. If I got something wrong, please comment for improve.<br>let’s connect on </em><a href="https://www.linkedin.com/in/myofficework/"><strong><em>Linkedin</em></strong></a><em> , </em><a href="https://github.com/myofficework000/"><strong><em>GitHub</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ec7f07302c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structure series: Binary Tree]]></title>
            <link>https://medium.com/@myofficework000/data-structure-series-binary-tree-d3ab5da012a0?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3ab5da012a0</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[binary-tree-traversal]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 21:44:12 GMT</pubDate>
            <atom:updated>2025-11-14T21:44:12.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*dqugOxCTbMvZWcHTfPMCHg.png" /></figure><p>Data structures are the backbone of computer programming, and <strong>trees</strong> are among the most fundamental structures used for organizing hierarchical data. In this article, we’ll explore <strong>Binary Trees</strong>, <strong>Binary Search Trees (BSTs)</strong>, and self-balancing trees like <strong>AVL Trees</strong> and <strong>Red-Black Trees</strong>, with real-world examples and use cases.</p><h3><strong>Binary tree</strong></h3><p>A <strong>Binary Tree</strong> is a tree data structure in which each node can have at most <strong>two children</strong>, commonly referred to as the <strong>left child</strong> and the <strong>right child</strong>.</p><h3>Key Concepts:</h3><ul><li><strong>Height of a tree</strong>: Number of nodes on the longest path from root to leaf. Height starts from <strong>1</strong>.</li><li><strong>Level of a tree</strong>: Distance of a node from the root. Root is at <strong>level 0</strong>.</li><li><strong>Maximum nodes at level </strong><strong>i</strong>: 2i2^i2i</li><li><strong>Maximum nodes in a binary tree of height </strong><strong>h</strong>: 2h−12^h - 12h−1</li></ul><h3>Example:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBxaSD2_mSSargLD9DzxgA.png" /></figure><p><strong>Note —<br></strong>Height of tree start from <strong>1</strong><br>Level of tree start from <strong>0</strong></p><ul><li>A tree with each node having at most 2 children.</li><li>Maximum number of nodes at level <strong>i</strong> is <strong>2^i</strong></li><li>Maximum number of nodes in a binary tree at height <strong>h</strong> is (<strong>2^h)-1</strong></li></ul><h3>Use Cases of Binary Trees:</h3><ol><li><strong>Hierarchical data representation</strong>: File systems, organizational charts.</li><li><strong>Expression trees</strong>: Used in compilers to evaluate expressions.</li><li><strong>Routing tables</strong>: In networking for efficient packet routing.</li></ol><h3><strong>Binary Search Tree</strong></h3><p>A <strong>Binary Search Tree</strong> is a <strong>binary tree</strong> with an additional property:</p><ul><li>The <strong>left child</strong> of a node contains only nodes with values <strong>less than the parent node</strong>.</li><li>The <strong>right child</strong> of a node contains only nodes with values <strong>greater than the parent node</strong>.</li></ul><p>This property allows efficient searching, insertion, and deletion.</p><h3>Example:</h3><p>20<br> / \<br> 10 30<br> / \ / \<br> 5 15 25 35</p><ul><li>Left child &lt; Root &lt; Right child</li><li>Searching for 25 will be faster because we only explore the relevant branch.</li></ul><h3>BST traversals</h3><h4>In-Order</h4><blockquote>visit left sub tree<br>then visit Node<br>then visit right subtree</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_yEM3d0lRDHp2uTYVGFkLA.gif" /></figure><h4>Pre-Order</h4><blockquote>visit node <br>then visit left sub tree<br>then visit right sub tree</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-azYnOVvcKScEs41o0l5dA.gif" /></figure><h4>Post-Order</h4><blockquote>visit left sub tree<br>then visit right sub tree<br>then visit node</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVSPAd2wjPVeZ9ZVT_xJzw.png" /></figure><h3>Use Cases of BST:</h3><ol><li><strong>Dynamic set operations</strong>: Searching, insertion, and deletion.</li><li><strong>Databases</strong>: Indexing data for quick lookup.</li><li><strong>Autocomplete systems</strong>: Suggesting words based on a prefix.</li></ol><h3>AVL Tree</h3><p>An <strong>AVL Tree</strong> is a <strong>self-balancing BST</strong>, named after its inventors <strong>Adelson-Velsky and Landis</strong>.</p><h3>Key Features:</h3><ul><li>For every node, the <strong>height difference</strong> between left and right subtrees is <strong>at most 1</strong>.</li><li>Ensures <strong>O(log n)</strong> time complexity for insertion, deletion, and search.</li></ul><h3>Why AVL Tree?</h3><ul><li>Regular BST can become skewed (like a linked list), leading to <strong>O(n)</strong> operations.</li><li>AVL tree rotations (left, right, left-right, right-left) maintain balance.</li></ul><h3>Use Cases of AVL Tree:</h3><ol><li><strong>High-frequency insert/delete operations</strong>: Banking transactions, stock systems.</li><li><strong>Memory-efficient search trees</strong> where balancing matters.</li></ol><h3>4. Red-Black Tree</h3><p>A <strong>Red-Black Tree</strong> is another type of <strong>self-balancing BST</strong> with <strong>color properties</strong>:</p><ul><li>Each node is either <strong>Red</strong> or <strong>Black</strong>.</li><li>Root is always Black.</li><li>No two consecutive red nodes.</li><li>Every path from root to null leaves has the same number of black nodes.</li></ul><h3>Advantages:</h3><ul><li>Guarantees <strong>O(log n)</strong> search, insertion, and deletion.</li><li>More flexible than AVL trees as it allows slight imbalance to reduce rotations.</li></ul><h3>Use Cases of Red-Black Tree:</h3><ol><li><strong>Java </strong><strong>TreeMap and </strong><strong>TreeSet implementation</strong>.</li><li><strong>Linux Kernel scheduler</strong> for task management.</li><li><strong>Associative containers in C++ STL</strong> (map, set).</li></ol><h3>Summary Comparison</h3><pre>| Tree Type      | Balanced | Search Time | Insert/Delete Time | Use Case Examples                    |<br>| -------------- | -------- | ----------- | ------------------ | ------------------------------------ |<br>| Binary Tree    | No       | O(n)        | O(n)               | File system, expression trees        |<br>| BST            | No       | O(log n)*   | O(log n)*          | Databases, autocomplete              |<br>| AVL Tree       | Yes      | O(log n)    | O(log n)           | High-frequency operations            |<br>| Red-Black Tree | Yes      | O(log n)    | O(log n)           | Java TreeMap, Linux kernel scheduler |</pre><h3>Real-Time Analogy:</h3><p>Think of a tree like a <strong>company hierarchy</strong>:</p><ul><li><strong>Binary Tree</strong>: Any structure where each manager can have up to two subordinates.</li><li><strong>BST</strong>: Organized so that smaller teams are on the left, bigger teams on the right.</li><li><strong>AVL Tree</strong>: Ensures no team grows too big or too small compared to others (balanced).</li><li><strong>Red-Black Tree</strong>: Allows small temporary imbalance but keeps overall hierarchy efficient.</li></ul><p>Binary trees and their variants are essential for <strong>efficient data storage, retrieval, and processing</strong>. Choosing the right tree structure depends on your <strong>use case, performance requirements, and frequency of updates</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTOMhR7yuUWTEqVD7SLG4Q.png" /></figure><h3>Further Reading &amp; Related Articles</h3><p>If you enjoyed this article and want to dive deeper into data structures, check out these posts from my series:</p><ul><li><a href="https://medium.com/@myofficework000/data-structure-series-linkedlist-bcb49dad8a59">Data Structure Series: LinkedList</a> — a practical walkthrough of singly‑linked lists (real‑world use cases and Kotlin implementation).</li><li><a href="https://medium.com/@myofficework000/data-structure-series-queue-data-structure-62b1c5bd335">Data Structure Series: Queue Data Structure</a> — explains queue operations, real‑time scenarios (ticket line, toll booth) and how to build one in Kotlin.</li><li><a href="https://medium.com/@myofficework000/understanding-the-stack-data-structure-and-evaluating-prefix-and-postfix-expressions-in-kotlin-2325cf435e53">Understanding the Stack Data Structure and Evaluating Prefix and Postfix Expressions in Kotlin</a> — covers stack fundamentals, plus how to evaluate prefix/postfix expressions using a stack implementation in Kotlin.</li></ul><p><em>Thank you for reading my article. I really appreciate </em>👏 <em>your response.</em></p><p><em>let’s connect on </em><a href="https://www.linkedin.com/in/myofficework/"><strong><em>Linkedin</em></strong></a><em> , </em><a href="https://github.com/myofficework000/"><strong><em>GitHub</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3ab5da012a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Idea to Impact: Software Engineering for Absolute Beginners]]></title>
            <link>https://medium.com/@myofficework000/from-idea-to-impact-software-engineering-for-absolute-beginners-517c94cce165?source=rss-67863a1cb6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/517c94cce165</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sdlc]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Abhishek Pathak]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 11:59:34 GMT</pubDate>
            <atom:updated>2025-10-06T11:59:34.209Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Written by Abhishek Pathak, Android Engineer &amp; Clean Architecture Enthusiast</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Ayla2ydQiLBTHXe" /><figcaption>Photo by <a href="https://unsplash.com/@foxxmd?utm_source=medium&amp;utm_medium=referral">Matt Foxx</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Software engineering isn’t about typing code. It’s about <strong>solving real problems</strong>, <strong>designing reliable systems</strong>, and <strong>turning ideas into products that people actually use</strong>.</p><p>Whether you’re a fresh college graduate, a beginner trying to enter the tech world, or someone switching careers, this guide will take you from <strong>zero understanding to full clarity</strong> on <em>how real-world software is built</em>.</p><p>We’ll do it with a <strong>real example</strong>, not theory.</p><h3>The Use Case — Let’s Build “Neighborhood Eats”</h3><p>Imagine a small-town food delivery platform:</p><ul><li>Users browse menus, place orders, and track delivery.</li><li>Restaurants accept orders.</li><li>Admins monitor everything.</li><li>Notifications, payments, order status updates — all working smoothly.</li></ul><p>This will be our running example. Every concept below ties back to <strong>how you would actually build this</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5gEdrg_XDzKButdk" /><figcaption>Photo by <a href="https://unsplash.com/@abillion?utm_source=medium&amp;utm_medium=referral">abillion</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Is Software Engineering (Really)?</h3><p>Software engineering is <strong>not just programming</strong> — programming is <em>typing instructions</em>.<br>Software engineering is <em>designing systems</em>.</p><p>It’s the disciplined process of <strong>analyzing problems, modeling solutions, and implementing them in a way that is scalable, testable, secure, and maintainable.</strong></p><p>A real engineer doesn’t only think about <strong>“Can I make this work?”</strong><br>They think:</p><ul><li><strong>Scalability</strong> — What happens when usage increases 100x?</li><li><strong>Fault Tolerance &amp; Reliability</strong> — What happens when a server crashes?</li><li><strong>Version Control &amp; Collaboration</strong> — Can multiple people work on this without chaos?</li><li><strong>Abstraction &amp; Modularity</strong> — Can I upgrade one part without breaking everything else?</li><li><strong>Documentation &amp; Knowledge Transfer</strong> — Will future engineers understand my decisions?</li><li><strong>Security &amp; Data Integrity</strong> — Can bad actors exploit this?</li><li><strong>Performance &amp; Resource Efficiency</strong> — Is it optimized or just “working”?</li></ul><blockquote><strong><em>Anyone can write code that runs.<br>A software engineer writes code that </em>survives<em>.</em></strong></blockquote><p>Software engineering blends <strong>computer science theory</strong> (algorithms, data structures, complexity) with <strong>real-world engineering practices</strong> (code reviews, CI/CD pipelines, design patterns, automated testing, observability).</p><p>It’s not just <em>how fast you code</em>, but <strong>how long your code lives without breaking.</strong></p><h3>The Software Development Life Cycle (SDLC)</h3><p>Here’s the lifecycle every real product — including <em>Neighborhood Eats </em>follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UgxhTSOS2qNldg41" /></figure><p><em>Fig: SDLC applied to our “Neighborhood Eats” food delivery system — showing Planning → Design → Implementation → Testing → Deployment → Monitoring &amp; Maintenance in a continuous loop. This cycle never truly ends — great software keeps evolving.</em></p><p>1. Planning &amp; Requirements</p><blockquote>Talk to users: <em>What do customers, restaurant owners, and delivery people actually need?</em></blockquote><blockquote>Write <strong>User Stories</strong> like:</blockquote><blockquote><em>“As a customer, I want to track my live order so I feel confident it’s coming.”</em></blockquote><blockquote>Identify <strong>MVP (Minimum Viable Product)</strong> — build only what’s essential.</blockquote><h3>2. System Design &amp; Architecture</h3><p>Decide:</p><blockquote><strong>Mobile + Backend API? Web app? Hybrid?</strong></blockquote><blockquote><strong>Where does data live?</strong></blockquote><blockquote><strong>How do we handle security? (Payments, personal info, logins)</strong></blockquote><p>Keep it clean using <strong>SOLID principles &amp; Clean Architecture, </strong>so future features don’t turn into nightmares.</p><h3>3. Implementation (Coding)</h3><blockquote>Use <strong>Git &amp; branches</strong><br>Write clean, readable code<br>Don’t overengineer, <em>simple is powerful if structured correctly</em></blockquote><h3>4. Testing</h3><p>Don’t skip! Qaulity check…..</p><blockquote><strong>Unit Tests</strong> → Small parts (e.g., calculating order total)</blockquote><blockquote><strong>Integration Tests</strong> → End-to-end (order flow)</blockquote><blockquote><strong>Manual Exploratory Testing</strong> → Try breaking it like a chaotic user</blockquote><h3>5. Deployment</h3><blockquote>Start manually (FTP / Firebase / EC2 / Vercel) → then</blockquote><blockquote>Move to <strong>CI/CD pipelines</strong> so code ships automatically after tests pass</blockquote><h3>6. Monitoring &amp; Maintenance</h3><p>Once users are on it — that’s when <em>the real work starts.</em></p><blockquote>Is the <strong>app crashing?</strong></blockquote><blockquote>Are <strong>orders getting stuck?</strong></blockquote><blockquote>Is the <strong>business making money?</strong></blockquote><p>You <strong>track → measure → fix → improve</strong>.</p><p>And then…</p><p>You loop <em>right back to planning.</em><br>That’s the circle of a true engineer.</p><h3>So now ways to cook final software?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cP-cDXSFtqazSDJOgiAWdA.png" /></figure><h3>A Simple 6-Month Learning Path for Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YbyliNn1SfqLQyykIMSmA.png" /></figure><h3>How it all truely started for me?</h3><p><strong>My Journey Begins</strong> in software didn’t start with big dreams, it started with <strong>curiosity</strong>.</p><p>Two decades ago, I saw a computer connected to the internet for the first time. Not just showing files but <em>pulling information out of thin air</em>. I needed to know <strong>how</strong>.</p><p>A teacher introduced me to something she called <em>“code”</em>. I typed a few strange characters, pressed enter… and the machine obeyed. It drew shapes. Opened windows. Reacted to me. That was it, I was hooked. While others played games, I played with logic.</p><p>Years later in university, I discovered that the <strong>official curriculum wouldn’t make me an engineer my curiosity would</strong>. While classmates waited for third-year electives, I spent my first-year break in a small town in Sri Lanka, learning Java for three months straight. No vacation. No shortcuts. Just tea, textbooks, and stubbornness.</p><p>Weekends became sacred. My friends left to relax; I stayed behind to build. Sometimes a single page in a programming book took an hour to understand but when it finally clicked, it felt like unlocking a superpower.</p><p>And that’s when I learned my greatest lesson:</p><blockquote><strong><em>Software engineering is not about being the smartest. It’s about being endlessly curious and refusing to give up on understanding.</em></strong></blockquote><p>Today, that same curiosity still drives me.</p><p>If you’re just starting your journey, remember <strong>you don’t need permission, a degree, or a perfect roadmap.</strong></p><p>You just need that one spark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tuVN0_-NSfu475yk" /><figcaption>Photo by <a href="https://unsplash.com/@hannynaibaho?utm_source=medium&amp;utm_medium=referral">Hanny Naibaho</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Thank you for reading my article. I really appreciate </em>👏 <em>your response.</em></p><p><em>Clap if this article helps you. </em>It means a lot to me.<em> If I got something wrong, please comment for improve.<br>let’s connect on </em><a href="https://www.linkedin.com/in/myofficework/"><em>Linkedin</em></a><em> , </em><a href="https://github.com/cheetahmail007"><em>GitHub</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517c94cce165" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>