← Microsoft bank

Microsoft · Question 12 · Strings

Implement strStr()

StringsJavacode⏱ O((h-n+1)*n)💾 O(1)
Product-based

Problem

Return the index of the first occurrence of needle in haystack, or -1 if not found.

Approach

Slide the needle across haystack comparing substrings.

Time O((h-n+1)*n)Space O(1)

How it works

  1. 1Empty needle matches at 0.
  2. 2Compare every window of needle length.

Sample input / output

Input:
sadbutsad
sad
Output:
0

Constraints

1 <= lengths <= 10^4; lowercase only.

Solution — read it, then walk it

Time O((h-n+1)*n)Space O(1)Loops 1Branches 2Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yes↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intstrStr(String haystack,String needle)if (needle.isEmpty())return 0DEFINE hLen =haystack.length(), nLen =needle.length()for (int i = 0; i <=hLen - nLen; i++)if(haystack.substring(i,i …RETURN iRETURN -1DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)String haystack = sc.next()String needle = sc.next()System.out.println(strStr(haystack,needle))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/15

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits