Edwin Zepeda, who works at the Grandes Ligas Dominican barbershop across from the building, said officers had to stop a woman from attacking Mr. Ayala. “Everybody was upset. Everybody wanted to know who it was,” he said. It took about 20 minutes for the man to be taken out of the building by officers, Mr. Zepeda said.

Sergeant Jones said Sunday that the police “have information that he is affiliated with MS-13,” but offered no additional details.

Victoria Nunez, an assistant district attorney, said during the arraignment that Mr. Ayala had admitted to detectives that he was in the bedroom, telling them, “I have never done anything like that before.” She said that the victim and Mr. Ayala were strangers, and that the girl had failed to identify Mr. Ayala in a lineup.

His lawyer, Anna Boksenbaum, a public defender, said Mr. Ayala lived with an aunt and uncle and two cousins in Brooklyn, and worked full time for his uncle’s air-conditioning company. Ms. Nunez said Mr. Ayala moved to Brooklyn from Virginia a few months ago. His next court date is Sept. 7.

Ms. Nunez said the girl saw Mr. Ayala perched on top of an air-conditioning unit outside of the window of the two-story home. After gaining entry, he climbed onto the top bunk where the 11-year-old had been sleeping and raped her, Ms. Nunez said. She said the victim’s brother was in the bottom bed.

Both parents were home but unaware of the break-in until they heard their daughter scream, Ms. Nunez said. Mr. Ayala went out the window, leaving behind a red Chicago Bulls cap that he was seen wearing on surveillance video in the vicinity before the attack, according to prosecutors.

A spokeswoman for the Immigration and Customs Enforcement agency said she was not able to immediately provide information on Mr. Ayala’s status.