<?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 Ankur Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Ankur Agrawal on Medium]]></description>
        <link>https://medium.com/@ankur.cse?source=rss-f587b9f06d5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ujd3LTgJoG2EDREDvDEY2g.jpeg</url>
            <title>Stories by Ankur Agrawal on Medium</title>
            <link>https://medium.com/@ankur.cse?source=rss-f587b9f06d5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:02:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankur.cse/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[Sliding Window explained with example — 1]]></title>
            <link>https://medium.com/@ankur.cse/sliding-window-explained-with-example-1-fe67684ae0fc?source=rss-f587b9f06d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe67684ae0fc</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[sliding-windows]]></category>
            <dc:creator><![CDATA[Ankur Agrawal]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 01:07:46 GMT</pubDate>
            <atom:updated>2023-01-12T17:36:14.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sliding Window explained with example — 1</h3><p>Sliding Window is one of the most commonly used technique to solve some of the complex computer problems in an optimized way around linear order of time complexity O(n). It’s very useful to know this concept and apply it wherever applicable whether you are writing a frontend or backend code where every millisecond counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*eWxxyqGBA5KlQctHBZsneg.png" /></figure><blockquote><strong><em>How easy/tough to understand</em></strong></blockquote><p>Wherever I was browsing, I found it bit hard to understand and then apply this concept in the problems, so I decided to create a series of articles to explain this concept in a simplest way possible.</p><blockquote><strong><em>Concept</em></strong></blockquote><p>Sliding Window means we iterate on the given set of literals/objects using two pointers where first pointer acts as a front wheel of the sliding window which expands the window and second pointer acts as a rear wheel which collapse the window.</p><blockquote><strong><em>Identify if problem belongs to Sliding Window paradigm</em></strong></blockquote><p>There are no defined rules which you can just follow to identify it but there are some guidelines if you follow can help you to identify if the given problem belongs to Sliding Window paradigm. <br>One such case is wherever you find it’s taking Quadratic time (n²) or more then there is a scope of doing it better and that’s where you need to see if this concept can be applied in the given problem. <br><strong>Example:</strong> if you are trying to extract a substring/range from a given input which follow certain condition(s) that means there is a high possibility this technique can be applied.</p><blockquote><strong><em>Problem Statment</em></strong></blockquote><p>Given a String <strong>s</strong> and Integer <strong>k</strong>, you can choose any character of the string and replace with any other character, you can do this operation at most <strong>k</strong> times. Return the longest substring containing same letter you get by performing above operation.<br><strong><em>Example 1:</em> </strong><br>s = “ABCAD”, k = 2, output = “ABCA”, Explanation: if you replace B and C with A then it will create longest substring AAAA.<br><strong><em>Example 2:</em> </strong><br>s = “AABABCA”, k = 1, output = “AABA”, Explanation: if you replace B with A then it will create longest substring AAAA.</p><ul><li><strong><em>Brute Force Approach<br></em></strong>In this approach you find all possible substrings of a given string (which is O(n²) ) and then for each substring you find the max length substring which follows the given condition.</li><li><strong><em>Sliding Window Approach <br></em></strong>There are two phases which are applied in this concept. <br>- <strong><em>Hunting Phase:</em></strong> In this phase depending on the given problem, either we keep hunting until we find first solution which meets the given condition or we keep hunting until the given condition becomes false.<br>- <strong><em>Catchup Phase:</em></strong> In this phase we perform the reverse of what we do in Hunting phase which help to find all the possible solutions.</li></ul><p><strong><em>Pseudo code using Sliding Window approach</em></strong></p><ul><li>Create two pointers left &amp; right assigned zero as default value.</li><li>Create a variable to hold the maximum frequency of characters in a given window, assigned zero as default value.</li><li>Create a map to track the frequency of each character in the given string.</li><li>Create a result array to hold the left &amp; right index values of the resulted substring.</li><li>Create a loop using the right pointer which will expand the window and will iterate till the length of the string.</li><li>Inside above loop, create a hunting logic to track the frequency of current character of the string and maximum frequency of the current window. This will go on until we find the length of current window which will have more than <strong>k </strong>different characters to be replaced.</li><li>Then create a catchup logic to increment the left pointer which will collapse the window.</li></ul><p><strong><em>Actual Code using Sliding Window approach</em></strong></p><pre>// Input: S:String, K:Int. <br>// Condition: Choose any character of the String and replace with any other<br>// other character, you can do this operation at most K times. <br>// Output: Return the longest substring containing same letter you can get after<br>// performing above operations. <br>// Example 1: Input: s=&quot;ABCAB&quot;, k=2, Output:&quot;ABCA&quot;, Explanation: if you replace B and C with A then it wil create longest substring AAAA.<br>// Example 2: Input: s=&quot;AABABBA&quot;, k=1, Output:&quot;AABA&quot;, Explanation: if you replace B with A, it will create longest substring containing AAAA.<br><br>fun longestSubContainSameChar(input:String,k:Int): String {<br>  var left = 0<br>  var right = 0<br>  var maxFreq = 0<br>  val map = mutableMapOf&lt;Char,Int&gt;()<br>  val result = arrayOf(0,0)<br>  <br>  while (right &lt; input.length) {<br>    // Hunting<br>    map[input[right]] = map.getOrDefault(input[right],0)+1<br>    maxFreq = Math.max(maxFreq,map[input[right]]!!)  <br>    val isValid = right-left+1 - maxFreq &lt;= k<br>    <br>    // Catchup<br>    if (!isValid) {<br>      map[input[left]] = map[input[left]]!! - 1<br>      left++<br>    }<br>    <br>    // Prepare Result<br>    if (right - left &gt; result[1]-result[0] ) {<br>       result[0] = left<br>       result[1] = right <br>    }    <br>    right++<br>  }<br>  println(&quot;[${result[0]},${result[1]}]&quot;)<br>  return input.substring(result[0],result[1]+1)<br>}<br><br>// Time Complexity O(n), Space Complexity O(n)</pre><p>Thats’ it until I create another article on the same topic.</p><p><em>Feel free to provide your comments. Appreciate if you click on bell icon (on top right) if you like the article and share the same.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe67684ae0fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-fill OTP in Android]]></title>
            <link>https://medium.com/@ankur.cse/auto-fill-otp-in-android-213d82e04f9b?source=rss-f587b9f06d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/213d82e04f9b</guid>
            <category><![CDATA[sms]]></category>
            <category><![CDATA[post]]></category>
            <category><![CDATA[autofill]]></category>
            <category><![CDATA[one-time-password]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ankur Agrawal]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 05:32:55 GMT</pubDate>
            <atom:updated>2022-01-04T07:49:03.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Y3E7Xpq0JUzvEiDK1cRL-g.jpeg" /><figcaption>Automatic OTP Authentication</figcaption></figure><p>This article will explain how to auto-fill OTP in android from any SMS text without requiring any extra app permissions.</p><blockquote><strong>Problem Statement</strong></blockquote><p>How to auto-fill OTP (One Time Password) code in SMS verification process in any Android app.</p><blockquote><strong>Challenges</strong></blockquote><ul><li>SMS text can be in any format.</li><li>Support in several device types and different Android versions.</li><li>Device settings can be different in different devices.</li></ul><blockquote><strong>Solutions</strong></blockquote><ol><li>Use of SMS Retrieval Api provided by Google (Particular use case only)</li><li>Use of SMS User Consent Api provided by Google (For all other use cases)</li></ol><p>The first solution is applicable to only those apps whose backend server itself sends the SMS text containing OTP having app hash in it. The app hash ensures the security that SMS text is accessible by only the app whose backend server has sent it. This is a good <em>use case of banking apps</em> which does the OTP based SMS verification.</p><p>The second solution is applicable to all those use cases where any app wants to access the OTP irrespective of where &amp; how the SMS text coming from.</p><blockquote><strong>My Use Case</strong></blockquote><p>During account verification process my app wants to auto-fill an OTP from SMS text which can come from any financial or non-financial institutions.</p><p>So I am going to explain how I implemented this using above second solution.</p><blockquote><strong>Workflow</strong></blockquote><p>This workflow is explained in below implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENMxI6MSujZ9rvcO2BFrsQ.png" /><figcaption>Auto-Fill OTP Workflow</figcaption></figure><blockquote><strong>Implementation</strong></blockquote><p>Follow these steps to implement auto-fill OTP from any type of SMS text originated from any system.</p><p>Add SMS User Consent Apis in your app</p><pre>implementation &#39;com.google.android.gms:play-services-auth:20.0.0&#39;<br>implementation &#39;com.google.android.gms:play-services-auth-api-  <br>                phone:18.0.0&#39;</pre><p>Create broadcast receiver to receive SMS User Consent Intent and show the consent to the user to grant SMS text read permission.</p><pre>class SmsUserConsentIntentBroadcastReceiver : BroadcastReceiver() {</pre><pre><em>/**<br>     * </em><strong><em>@param </em></strong><em>context The Context in which the receiver is running.<br>     * </em><strong><em>@param </em></strong><em>intent The Intent being received.<br>     */<br>    </em>override fun onReceive(context: Context?, intent: Intent?) {<br>        if (intent?.<em>action </em>== SmsRetriever.<em>SMS_RETRIEVED_ACTION</em>) {<br>            val bundle = intent.<em>extras<br>            </em>val smsRetrieverStatus = <br>                bundle?.get(SmsRetriever.<em>EXTRA_STATUS</em>) as? Status<br>            when (smsRetrieverStatus?.<em>statusCode</em>) {<br>                CommonStatusCodes.<em>SUCCESS </em>-&gt; {<br>                    // Get SMS User Consent intent<br>                    val consentIntent =<br>                    bundle.getParcelable&lt;Intent&gt;<br>                    (SmsRetriever.<em>EXTRA_CONSENT_INTENT</em>)<br>                    kotlin.<em>runCatching </em><strong>{<br>                    </strong>/* smsUserConsentActivityLauncher is defined     <br>                       below<br>                    */<br>                <em>smsUserConsentActivityLauncher</em>.launch(consentIntent)                      <br>                    <strong>}</strong>.<em>onFailure </em><strong>{                        </strong><br>                    <strong>}<br>                </strong>}       <br>                CommonStatusCodes.<em>TIMEOUT </em>-&gt; Log.warn(&quot;SMS User <br>                  Consent Listener didn&#39;t receive the required SMS <br>                  text containing OTP in 5 mins after started <br>                  listening and so it couldn&#39;t broadcast the SMS <br>                  User Consent Intent&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>Register SMS User Consent Intent broadcast receiver</p><pre>val intentFilter = IntentFilter(SmsRetriever.<em>SMS_RETRIEVED_ACTION</em>)<br>// SmsRetriever.SEND_PERMISSION means this receiver will receive the  <br>   intent originated from SmsRetriever api only<br>fragmentActivity.registerReceiver(<br>    S<em>msUserConsentIntentBroadcastReceiver()</em>, intentFilter, <br>    SmsRetriever.<em>SEND_PERMISSION</em>, null)</pre><p>Start SMS User Consent Listener</p><pre>/* Start SMS User Consent Listener which will <strong><em>broadcast SMS User   <br>   Consent Intent</em></strong> only if meet following criteria - <br>   1: sms text contains a 4-10 character alphanumeric string with at <br>     least one number.<br>   2: sms was sent by a phone number that&#39;s not in user&#39;s contacts.<br>   3: The API will look for the One Time Code for a maximum time of <br>      5 minutes. <br>   NOTE: The listener looks for only one sms text containing OTP and <br>   so broadcast only one SMS User Consent Intent. <br>*/<br>val smsRetrieverClient = SmsRetriever.getClient(context)<br>smsRetrieverClient.startSmsUserConsent(null).addOnSuccessListener <strong>{<br>        </strong><em>OnSuccessListener</em>&lt;Unit&gt; <strong>{<br>          </strong>Toast.makeText(getApplicationContext(), &quot;Listener <br>            started&quot;, Toast.LENGTH_LONG).show();<br>        <strong>}<br>    }</strong>.addOnFailureListener <strong>{<br>        </strong><em>OnFailureListener </em><strong>{ </strong>it: Exception<strong><br>          </strong>Toast.makeText(getApplicationContext(), &quot;Listener <br>            failed&quot;, Toast.LENGTH_LONG).show();<br>        <strong>}<br>    }</strong></pre><p>Register for activity result of SMS User Consent Intent</p><pre>// activityResultCallback will be defined later<br>val smsUserConsentActivityLauncher = <br>     fragment.registerForActivityResult( <br>         ActivityResultContracts.StartActivityForResult(),   <br>         activityResultCallback<br>     )</pre><p>Show SMS User Consent Activity as BottomSheet</p><p>On receive of SMS containing OTP, the broadcast receiver implemented above will show launch activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*wqyKsRQ6JZgPTgj34n8DYg.png" /></figure><p>Read SMS text message once user clicks Allow in above screen and then extract OTP from the message to auto-fill.</p><pre>fun getSmsUserConsentActivityResultCallback() = object : <br>    ActivityResultCallback&lt;ActivityResult&gt; {<br>      var smsMessage: String? = null<br><br>      <em>/**<br>      * Called when SMS User Consent activity result is available<br>      */<br>      </em>override fun onActivityResult(activityResult: ActivityResult?) <br>      {<br>        // When user clicks Allow button in above screen<br>        if (activityResult?.<em>resultCode </em>== Activity.<em>RESULT_OK</em>) {<br>            activityResult.<em>data</em>?.<em>let </em><strong>{ </strong>data <strong>-&gt;<br>                </strong>smsMessage = <br>                 data.getStringExtra(SmsRetriever.<em>EXTRA_SMS_MESSAGE</em>)<br>                smsMessage?.<em>let </em><strong>{ </strong>it <strong>-&gt;<br>                    </strong>// getOtpFromMessage() is defined below<strong>                    <br>                    </strong>val otp = <em>getOtpFromMessage</em>(it)<br>                    otp?.<em>let </em><strong>{<br>                        </strong>mfaView.autofillOTP(it)<br>                    <strong>}<br>                }<br>            }<br>        </strong>} else {<br>            Log.<em>info(</em>&quot;User denied the SMS read consent to access OTP <br>              code&quot;)<br>        }<br>     }<br>  }</pre><pre>fun getOtpFromMessage(message: String): String? {<br>    // This will match any &gt;=4 digits number in the message<br>    val pattern = Pattern.compile(&quot;\\(|\\)|\\d{4,}&quot;)<br>    val matcher = pattern.matcher(message)<br>    return if (matcher.find()) matcher.group(0) else null<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*kfEjqZe6ZJmf9jOPYEffWw.png" /></figure><blockquote><strong>Advantages</strong></blockquote><ul><li>Work on every device type and in every Android version.</li><li>SMS text can be in any format, it should contain minimum 4 digit OTP.</li><li>SMS text can be originated from any system.</li><li>Doesn’t need any extra settings from user in any device.</li></ul><p>Thats’ it.</p><p>Feel free to provide comments if you have any.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213d82e04f9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>